下面是一个 pgfplots 代码,用于绘制三条曲线,并带有图例:
\documentclass{article}
\usepackage{pgf, tikz, pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend columns=2,]
\addplot {x};
\addlegendentry{$x$}
\addplot {x+4};
\addlegendentry{$x$+4}
\addplot {-x+4};
\addlegendentry{$-x$+4}
\end{axis}
\end{tikzpicture}
\end{document}
结果如下,图例出现在两列上:
图例条目逐行显示在图例框中。我想逐列显示它们,如下所示(链接的图片已使用 gimp 手动设置):
有办法吗?
答案1
作为一种简单的方法,您可以使用transpose legend
将列转换为行的选项:
\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend columns=2, transpose legend]
\addplot {x};
\addlegendentry{$x$}
\addplot {x+4};
\addlegendentry{$x$+4}
\addplot {-x+4};
\addlegendentry{$-x$+4}
\end{axis}
\end{tikzpicture}
\end{document}
请注意,使用时transpose legend
,该选项legend columns
实际上会采用您可能需要调整的行数以适应更长的图例:
\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend columns=3, transpose legend]
\addplot {x};
\addlegendentry{$x$}
\addplot {x+4};
\addlegendentry{$x$+4}
\addplot {-x+4};
\addlegendentry{$-x$+4}
\addplot {-x+5};
\addlegendentry{$-x$+5}
\addplot {-x+6};
\addlegendentry{$-x$+6}
\end{axis}
\end{tikzpicture}
\end{document}