38

I am using the awesome pgfplots package to draw some plots. I usually use \addlegendentry and get a nice default legend box. There are some options for legend box placement and layout (e.g. number of columns).

For some plots I would like to add a title inside the legend box.

Could not find the something about this in the manual. Does anyone know what is the way to customize the legend box?

1 Answer 1

33

You could perhaps use the \addlegendimage command, as in this discussion from the pgfplots-features mailing list.

An example, with a small \hspace hack to place the title more centered in the legend box:

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend pos=south east]
   \addlegendimage{empty legend}
   \addplot {sqrt(x)}; 
   \addplot {ln(x)}; 

   \addlegendentry{\hspace{-.6cm}\textbf{A title}}
   \addlegendentry{$\sqrt{x}$}
   \addlegendentry{$\ln{x}$}
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

For variety, here's a couple of more manual approaches. In each case the legend and title are separate entities, and the frame drawn afterwards.

\documentclass[border=5mm,tikz]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend style={at={(rel axis cs:0.9,0.1)},above left,name=legend,draw=none}]
   \addplot {sqrt(x)}; 
   \addplot {ln(x)}; 

   \addlegendentry{$\sqrt{x}$}
   \addlegendentry{$\ln{x}$}
\end{axis}
   \node [above,font=\bfseries] (legendtitle) at (legend.north) {Legend title};
   \node [fit=(legendtitle)(legend),draw,inner sep=0pt] {};
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[legend style={draw=none,legend to name=leg}]
   \addplot {sqrt(x)}; 
   \addplot {ln(x)}; 

   \addlegendentry{$\sqrt{x}$}
   \addlegendentry{$\ln{x}$}

   % place legend
   \node [above left] (L) at (rel axis cs:0.9,0.1) {\ref{leg}};
   % Add title
   \node [above,font=\bfseries] (LT) at (L.north) {Legend title};
   % if needed, add frame
   \node [fit=(L)(LT),draw,inner sep=0pt] {};
\end{axis}
\end{tikzpicture}
\end{document}
2
  • Thanks for this great answer. If I understood correctly, you need to pair \addlegendimage with addlegendentry and insert them in the correct sequence... An addlegendtitle would be so much more convenient!
    – PatrickT
    Sep 28, 2017 at 17:10
  • 1
    @PatrickT That is true, but no such feature is available at the moment. You could make a feature request at sourceforge.net/p/pgfplots/feature-requests/?source=navbar Sep 28, 2017 at 17:16

You must log in to answer this question.

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