# pgfplots: alignment and size of math in legend

The legend entries created by a more complex math formula as in this example are overlapping and the alignment to the lines is wrong.

\documentclass[]{scrbook}

\usepackage{pgfplots}
\usepackage{amsmath}

\begin{document}
\pgfplotsset{width=0.8\textwidth, height=0.6\textwidth}
\centering
\begin{tikzpicture}
\begin{axis}[scale only axis,samples=2000,
/pgfplots/enlargelimits=false,
legend style={legend pos=north west}]
\legend{$f(x) = 5\exp\left(-\left(\dfrac{x-5\pi}{2.5\pi}\right)^2\right) \sin(2x) + x$,
$f(x)_\text{fit} = x$}
\end{axis}
\end{tikzpicture}
\end{document}


-
Or you can shift the formula slightly with \legend{{\raisebox{1.5ex}{$f(x) = 5\exp\left(-\left(\dfrac{x-5\pi}{2.5\pi}\right)^2\right)\sin(2x) + x$}},$f(x)_\text{fit} = x$} –  percusse Mar 19 '12 at 19:46

The alignment can be changed using

legend cell align=left,


The other issues can be changed in a variety of different ways- in what follows I didn't use samples=2000 as it increases the compiling time quite significantly- the question was independent from this though.

• using legend style={legend pos=north west,font=\tiny} gives

\begin{tikzpicture}
\begin{axis}[scale only axis,
legend cell align=left,
/pgfplots/enlargelimits=false,
legend style={legend pos=north west,font=\tiny}]
\legend{$f(x) = 5\exp\left(-\left(\dfrac{x-5\pi}{2.5\pi}\right)^2\right) \sin(2x) + x$,
$f(x)_\text{fit} = x$}
\end{axis}
\end{tikzpicture}

• Using @percusse's \raisebox idea (permission to post given during chat- thanks @percusse!)

\legend{\raisebox{2.5ex}{$f(x) = 5\exp\left(-\left(\dfrac{x-5\pi}{2.5 \pi}\right)^2\right)\sin(2x) + x$}


• Using a blank line in the legend

\begin{tikzpicture}
\begin{axis}[scale only axis,
/pgfplots/enlargelimits=false,
legend cell align=left,
legend style={legend pos=north west,font=\tiny}]
\addlegendentry{$f(x) = 5\exp\left(-\left(\dfrac{x-5\pi}{2.5\pi}\right)^2\right)$}
\addlegendentry{$f(x)_\text{fit} = x$};
\end{axis}
\end{tikzpicture}

• Or you could put the legend in the caption using \label and \ref

\begin{figure}
\begin{tikzpicture}
\begin{axis}[scale only axis,
legend cell align=left,
/pgfplots/enlargelimits=false,
legend style={legend pos=north west,font=\tiny}]
\caption{\ref{plot:firstplot} is $f(x) = 5\exp\left(-\left(\dfrac{x-5\pi}{2.5\pi}\right)^2\right)\sin(2x) + x$ and
\ref{plot:secondplot} is $f(x)_\text{fit}=x$}

If you add an example with the raisebox code I could accept your answer. I use now font=\smalland \raisebox{2.5ex}{...} –  Matthias Pospiech Mar 19 '12 at 21:46
@MatthiasPospiech the \raisebox... wasn't my idea, it was @percusse's, so I'm not sure if I should make that edit. You could still upvote my answer though :) –  cmhughes Mar 19 '12 at 23:32