4

I'm drawing a simple scatter plot with pgfplots, which also includes a legend as shown in the upper part of the picture next.

enter image description here

However, I find the horizontal spacing odd because the distance between the symbol and the corresponding description is the same as to the next description. I would like to have it like "faked" in the lower part of the picture.

A simple example is produced by the following code. Here, the descriptions are a,b,c,d.

\documentclass{scrartcl}
\usepackage{pgfplots}
\begin{document}

\begin{tikzpicture}
    \begin{axis}[legend columns=-1, legend pos=outer north east]
        \addplot+ coordinates {(0,0) (0,1)};
        \addplot+ coordinates {(1,0) (0,0)};
        \addplot+ coordinates {(0,0) (1,1)};
        \addplot+ coordinates {(1,1) (0,0)};
        \legend{a,b,c,d};
    \end{axis}
\end{tikzpicture}

\end{document}

If I understand the manual correctly, the legend is composed of a matrix. However, I could not figure out how to change the spacing accordingly. Your help is much appreciated ;)

Dan
  • 591

1 Answers1

4

The easiest way to do this is to specify the text width for the labels in the legend. See the second example below.

Sample output

\documentclass{scrartcl}
\usepackage{pgfplots}
\begin{document}

\begin{tikzpicture}
  \begin{axis}[legend columns=-1, legend pos=outer north east]
        \addplot+ coordinates {(0,0) (0,1)};
        \addplot+ coordinates {(1,0) (0,0)};
        \addplot+ coordinates {(0,0) (1,1)};
        \addplot+ coordinates {(1,1) (0,0)};
        \legend{a,b,c,d};
    \end{axis}
\end{tikzpicture}

\begin{tikzpicture}
  \begin{axis}[legend columns=-1, legend pos=outer north east,
    legend style={text width=2em,text height=1.5ex,text depth=.5ex}]
        \addplot+ coordinates {(0,0) (0,1)};
        \addplot+ coordinates {(1,0) (0,0)};
        \addplot+ coordinates {(0,0) (1,1)};
        \addplot+ coordinates {(1,1) (0,0)};
        \legend{a,b,c,d};
    \end{axis}
\end{tikzpicture}

\end{document}

I have added a text height to make all the letters sit on an even baseline. For uniformity I have also specified a text depth, even though pgfplots already sets one.

Andrew Swann
  • 95,762
  • 1
    Thanks! Your solution works fine for description that are of the same length. If this is not the case, the distances still don't fit exactly. – Dan Sep 01 '13 at 17:06
  • 2
    @Dan: A way of setting the spacing between the legend entries (instead of the width of the legend entries) is given at http://tex.stackexchange.com/questions/18152/how-can-i-adjust-the-horizontal-spacing-between-legend-entries-in-pgfplots – Jake Sep 01 '13 at 19:55
  • Thank you very much! That works fine! I'm just wondering why I did not find the question you're referring to ... have to do better research next time. – Dan Sep 01 '13 at 21:45