TikZ legend in caption

The image generated by the \ref command is already neatly sized and positioned, there's no need to wrap it in an additional TikZ picture:

\caption{This is a plot about curves in color such as $f(x)=0.4 x$ (\ref{p4}),  $f(x)=0.5 x$(\ref{p5}) and $f(x)=0.6 x$(\ref{p6})}

yields


If you add [inner sep=0] to each node declaration, everthing works as is. TikZ adds a little space around each node automatically, which is where the extra space comes from.

Concretely,

\savebox{\captionA}{(\small\tikz[baseline]\node at (0,2.5pt){\ref{p4}};)}%

becomes

\savebox{\captionA}{(\small\tikz[baseline,inner sep=0pt]\node at (0,2.5pt){\ref{p4}};)}%