考虑一下 LaTeX 代码
\documentclass{standalone}
\usepackage{tikz,pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend columns=2,
legend style={at={(0.5,1.02)},anchor=south,
legend cell align=right},]
\addlegendimage{empty legend}
\addlegendentry{Explanation of the legend}
\addplot[red,
mark=o]
coordinates{(1,1) (2,5) (3,7) (4,8) (5,12)};
\addlegendentry{$f(x)$}
\addplot[blue,
mark=diamond]
coordinates{(1,2) (2,6) (3,4) (4,7) (5,10)};
\addlegendentry{$g(x)$}
\addplot[black,
mark=triangle]
coordinates{(1,6) (2,7) (3,5) (4,6) (5,1)};
\addlegendentry{$h(x)$}
\end{axis}
\end{tikzpicture}
\end{document}
其输出如下所示。您可能会发现,尽管我已将 应用于legend cell align=right
图例单元格的右对齐,但该规则仅适用于单元格的描述,而不适用于其线条样式。具体来说,我希望图例中带有菱形的蓝线接近其右对齐描述g(x)
。我该怎么做?
答案1
尝试这个:
\documentclass[border=5pt]{standalone}
\usepackage{tikz,pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend columns=4,
legend style={at={(0.5,1.02)},anchor=south},scale=1.25]
\addlegendimage{empty legend}
\addlegendentry{Explanation of the legend}
\addplot[red,
mark=o]
coordinates{(1,1) (2,5) (3,7) (4,8) (5,12)};
\addlegendentry{$f(x)$}
\addplot[blue,
mark=diamond]
coordinates{(1,2) (2,6) (3,4) (4,7) (5,10)};
\addlegendentry{$g(x)$}
\addplot[black,
mark=triangle]
coordinates{(1,6) (2,7) (3,5) (4,6) (5,1)};
\addlegendentry{$h(x)$}
\end{axis}
\end{tikzpicture}
\end{document}