I use tabular legends for my graphs in pgfplots. At least three posts give ways to do that: Tabular like legend,
Custom legend and Tabular legend. I like the syntax where a \label is given to the curves, called in a \matrix after \end{axis}.
However, I often need to define the legend entries "by hand" with \addlegendimage, which is then labeled and reference to. Here's an example:
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{
matrix,
}
\pgfplotsset{
compat=newest,
every axis plot post/.append style={
every mark/.append style={solid}, % avoid dashed markers
}
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
title={$y=a \cdot x + b$},
xlabel=$x$,
ylabel=$y$,
]
\addplot+[domain=-1:2, samples=10, mark=o, dashed] {1*x+1};
\addplot+[domain=-1:2, samples=10, mark=o, solid] {1*x+2};
\addplot+[domain=-1:2, samples=10, mark=square, dashed] {2*x+1};
\addplot+[domain=-1:2, samples=10, mark=square, solid] {2*x+2};
\addlegendimage{dashed} % define by hand a legend image
\label{plot:dashed} % label it
\addlegendimage{solid}
\label{plot:solid}
\addlegendimage{only marks, mark=o}
\label{plot:o}
\addlegendimage{only marks, mark=square}
\label{plot:square}
\coordinate (legend) at (axis description cs:1.03,1);
\end{axis}
\matrix[
draw,
matrix of nodes,
anchor=north west,
]
at (legend) {
Slope & $a$ & $1/a$ \\
\ref{plot:o} & 2 & 0.5 \\
\ref{plot:square} & 1 & 1 \\
Origin & $b$ & $1/b$ \\
\ref{plot:solid} & 2 & 0.5 \\
% call the image. It would better to create it by hand here, no?
\ref{plot:dashed} & 1 & 1 \\
};
\end{tikzpicture}
\end{document}
It sounds strange to define "by-hand" a \addlegendimage with a \label and then call it in the matrix with \ref.
As we're still in the tikzpicture, is there a command to directly generate the legend images within the matrix?
