[Tex/LaTex] TikZ legend in caption

captionslegendpgfplots

I have adapted a piece of code that I found on the Q&A forum multiple legends in pgfplots as follows in order to include the legend of a drawing directly into the caption:

EDIT 1

\documentclass[a4paper]{book}
\usepackage{lipsum}
\usepackage{pgfplots}
\usepackage[left=3.8cm,right=3.8cm,a4paper]{geometry}
\pgfplotsset{compat=1.3}
\begin{document}
\lipsum[1-2]
\begin{figure}[!ht]
\centering
\begin{tikzpicture}
\begin{axis}[height=6cm,width=8.5cm,grid=major,xlabel=$x$,ylabel=$f(x)$,tick label style={font=\small},label style={font=\small},title style={font=\small},every axis title shift=0pt,max space between ticks=30,major tick length=0cm,minor tick length=0cm,enlargelimits=false,]
\addplot expression[domain=-6:6] {0.4*x};\label{p4}
\addplot{0.5*x};\label{p5}
\addplot{0.6*x};\label{p6}
\end{axis}
\end{tikzpicture}\par
% boxes for caption 1
\newbox{\captionA}%
\savebox{\captionA}{(\small\tikz[baseline]\node at (0,2.5pt){\ref{p4}};)}%
\newbox{\captionB}%
\savebox{\captionB}{(\small\tikz[baseline]\node at (0,2.5pt){\ref{p5}};)}%
\newbox{\captionC}%
\savebox{\captionC}{(\small\tikz[baseline]\node at (0,2.5pt){\ref{p6}};)}%
\caption{This is a plot about curves in color such as $f(x)=0.4 x$\usebox{\captionA},  $f(x)=0.5 x$\usebox{\captionB} and $f(x)=0.6 x$\usebox{\captionC}}
\end{figure}
\lipsum[1-2]
\end{document}

but as may you may notice, the brackets around the colored ref are a bit too far: is it possible to control this?

EDIT 2: final answer

\documentclass{book}
\usepackage{lipsum}
\usepackage{caption}
\usepackage{pgfplots}
\pgfplotsset{compat=1.3}
\tikzset{pointille/.style={dash pattern = on 2pt off 2pt on 6pt off 2pt}}
\tikzset{points/.style={dash pattern = on 1pt off 1pt}}
\tikzset{tirets/.style={dash pattern = on 5pt off 5pt}}

\begin{document}
\lipsum[1]
\begin{figure}[!ht]
\centering
\captionsetup{width=9.5cm}
\pgfplotsset{every axis plot post/.append style={mark=none,line width=1.5pt}}
\begin{tikzpicture}
\begin{axis}[height=7cm,width=9cm,grid=major,xlabel=$x$,ylabel=$f(x)$,
tick label style={font=\footnotesize},label style={font=\small},max space between ticks=45, major tick length=0cm,minor tick length=0cm,enlargelimits=false,]
\addplot[tirets,color=blue]{2*x};\label{p4}
\addplot[pointille,color=green]{0.5*x*x};\label{p5}
\addplot[points,color=red]{-0.125*x*x*x};\label{p6}
\end{axis}
\end{tikzpicture}
\caption[Caption in ToC]{This is a plot about colored curves: $f(x)=2 x$ (\ref{p4}),  $f(x)=0.5 x^2$ (\ref{p5}), and $f(x)=-0.125 x^3$ (\ref{p6})}
\end{figure}
\lipsum[1]
\end{document}

enter image description here

Best Answer

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