3

Consider the MWE below. How can we adjust the size of the box around the legend such that it matches the contents?

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[width=6cm]
    \addplot[domain=-2:2] {1};
    \addlegendentry{$f(x)=\frac{1}{2\pi_{2_2}}$};
    \addlegendentry{$f(x)=1$};
  \end{axis}
  \begin{scope}[shift={(5,0)}]
  \begin{axis}[width=6cm]
    \addplot[domain=-2:2] {1};
    \addlegendentry{$f(x)=1$};
  \end{axis}
\end{scope}
\end{tikzpicture}
\end{document}

As you can see on the image below (left) the depth of the material is sort of ignored.

enter image description here

daleif
  • 54,450

1 Answers1

2

There are various approaches which work more or less well for different cases.

1) inner ysep

A simple solution could be set the inner y-separation legend style={inner ysep=5pt}:

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[width=6cm, legend style={inner ysep=5pt}]
    \addplot[domain=-2:2] {1};
    \addlegendentry{$f(x)=\frac{1}{2\pi_{2_2}}$};
    \addlegendentry{$f(x)=1$};
  \end{axis}
  \begin{scope}[shift={(5,0)}]
  \begin{axis}[width=6cm, legend style={inner ysep=5pt}]
    \addplot[domain=-2:2] {1};
    \addlegendentry{$f(x)=1$};
  \end{axis}
\end{scope}
\end{tikzpicture}
\end{document}

However you also increase the gap to the upper frame border:

enter image description here

2) text depth

legend style={nodes={text depth=1.5mm}}

Is a very elegant solution mentioned by @percusse in the comments. Some extra space is added below every item, also the last item, which maybe not desired in case the last item is no fraction.

3) row sep

If you have multiple legend entries (which you probably have, otherwise the legend is pointless) - and the last entry does not contain a fraction, then changing the row sep is the better option, as it doesn't adda gap neither on the top nor on bottom, just inbetween the items:

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[width=6cm,legend style={row sep=5pt}]
    \addplot[domain=-2:2] {1};
    \addplot[domain=-2:2] {1};
    \addlegendentry{$f(x)=\frac{1}{2\pi_{2_2}}$};
    \addlegendentry{$f(x)=1$};
  \end{axis}
  \begin{scope}[shift={(5,0)}]
  \begin{axis}[width=6cm]
    \addplot[domain=-2:2] {1};
    \addlegendentry{$f(x)=1$};
  \end{axis}
\end{scope}
\end{tikzpicture}
\end{document}

enter image description here

4) parbox

Fiddling around with a \parbox could also be an option, case you just need a solution for a single particular item

\addlegendentry{\parbox[b][0.5cm][c]{2cm}{$f(x)=\frac{1\vphantom{2\pi^{2^2}}}{2\pi_{2_2}}$}};

5) semitransparent

Because of troubles like that I personally prefer something like:

\tikzset{semitransparent/.style = {draw=none, fill = white, fill opacity=0.8, text opacity = 1}}

and then

legend style={semitransparent}

over boxes.