4

I am looking for a simple way to have multiple alignments in a TikZ legend.

I have the following code which produces a TikZ figure:

\documentclass[11pt,a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\begin{figure}
\begin{tikzpicture}
\begin{axis}[%
width=4in,height=3in,at={(0in,0in)},
scale only axis,
xmin=0,xmax=10,ymin=0,ymax=5,
legend style={legend cell align=left,align=left},
]
\addplot [color=red]
  table[row sep=crcr]{%
0   5\\
10   0\\
};
\addlegendentry{First: 1};
\addplot [color=blue]
  table[row sep=crcr]{%
0   4\\
10   1\\
};
\addlegendentry{Second: 2};
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}

The figure looks like this:

enter image description here

This is fine except that the numbers in the legend should be aligned. So what I want to have is this:

enter image description here

How can I achieve such alignment within the TikZ legend?

1 Answer 1

3

The easy solution is to pick or compute a width and use \makebox or \hbox to to create each legend entry.

You can also create your own legend using a tabular. See here

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\newlength{\tempdima}
\begin{document}
%\begin{figure}
\settowidth{\tempdima}{Second:\quad 2}% longest entry
\begin{tikzpicture}
\begin{axis}[%
width=4in,height=3in,at={(0in,0in)},
scale only axis,
xmin=0,xmax=10,ymin=0,ymax=5,
legend style={legend cell align=left,align=left},
]
\addplot [color=red]
  table[row sep=crcr]{%
0   5\\
10   0\\
};
\addlegendentry{\hbox to \tempdima {First:\hfill 1}};
\addplot [color=blue]
  table[row sep=crcr]{%
0   4\\
10   1\\
};
\addlegendentry{\makebox[\tempdima]{Second:\hfill 2}};
\end{axis}
\end{tikzpicture}
%\end{figure}
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .