9

I am a new user to PGFPlots so I have the following question: I draw a ellipse in TikZ and I want to add a legend for it. However, I found the \addlegendentry is only for \addplot. Then, how can I add a legend for my curve?

\tikzsetnextfilename{1a}
\begin{tikzpicture}
\begin{axis}[
 xlabel = $\dfrac{M}{M_{bend}}$,
 ylabel = $\dfrac{P}{P_{burst}}$,
  xmin=0,xmax=1.2,
  ymin=0,ymax=1.2,
 ymajorgrids=true,
 xmajorgrids=true,
 grid style=dashed,
 label style={font=\tiny},
 tick label style={font=\tiny},
 legend style={font=\small},
 legend cell align=left,
 legend pos=north east
  ]
 \addplot+[color=red,
 line width=0.3mm] 
 (axis cs:0,0)
   ellipse [
  x radius=0.950052, y radius=0.945021];
\addlegendentry{Analytical results}
 \end{axis}
\end{tikzpicture}

I read about the customized legend from Customize legend position in PGFplots axis environment, but I have no idea about how to put this in an axis environment.

1 Answers1

10

You can use \addlegendimage to add a legend for a \draw command. The argument to \addlegendimage is just the same style parameters used in the draw, e.g. red,line width=0.3mm. The problem with using \draw like this is however that the scale is wrong, as it doesn't use the coordinate system of the axis.

Another option here is to plot the ellipse with addplot, which gives the correct size.

\documentclass[tikz,border=5mm]{standalone}
\usepackage{pgfplots,amsmath}

\begin{document}  
\begin{tikzpicture}
\begin{axis}[
 xlabel = $\dfrac{M}{M_{\mathrm{bend}}}$,
 ylabel = $\dfrac{P}{P_{\mathrm{burst}}}$,
  xmin=0,xmax=1.2,
  ymin=0,ymax=1.2,
 ymajorgrids=true,
 xmajorgrids=true,
 grid style=dashed,
 label style={font=\tiny},
 tick label style={font=\tiny},
 legend style={font=\small},
 legend cell align=left,
 legend pos=north east
  ]

\draw[color=red,
 line width=0.3mm] 
 (axis cs:0.6,0.6) % moved to middle of plot to make it more visible
   ellipse [
  x radius=0.950052, y radius=0.945021];

\addlegendimage{line width=0.3mm,color=red}
\addlegendentry{Analytical results}

\addplot [variable=\t,samples=200,domain=0:360] ({0.950052*cos(t)},{0.945021*sin(t)});
\addlegendentry{Parametric analytic}
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

Torbjørn T.
  • 206,688
  • 1
    Thank you very much. The reason I use \draw is I can't find a good way to plot ellipse by \addplot. Then, problem solved! – user51508 May 12 '14 at 06:30