是否可以自定义图例键的样式(图例中指示线型为实线、虚线、点线等的部分)?
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}[domain=0:10, no marks]
\addplot+[red, solid] {x - 1}; \label{one}
\addplot+[blue, solid] {2*x - 3}; \label{two}
\addlegendentry{$m = 2$}
\addlegendentry{$m = 1$}
\addplot+[red, densely dotted] {x - 0}; \label{three}
\addplot+[blue, densely dotted] {2*x + 2}; \label{four}
% Rough look of desired legend
\draw[densely dotted, blue] (0, 11) -- (0.5, 11);
\draw[solid, blue] (0.5, 11) -- node[xshift=0.1cm, right] {$m = 1$} (1, 11);
\draw[densely dotted, red] (0, 13) -- (0.5, 13);
\draw[solid, red] (0.5, 13) -- node[xshift=0.1cm, right] {$m = 2$} (1, 13);
\end{axis}
\end{tikzpicture}
\end{document}
我不想为每条曲线都设置一个图例,而是希望有两个图例条目,分别表示实线和虚线的线斜率 $m$。因此,图例条目 $m = 2$ 将由一条红线段引用,其中一半是虚线,另一半是实线。可能类似于\addlegendimage{custommarker, red}
。是否有执行此操作的流程?
这问题不同,因为我对创建非默认图例键感兴趣。整个图例可以从头开始创建,但想知道是否有内置方法可以做到这一点(如果可以轻松提取图例框、空白等的默认尺寸,那么从头开始可能会更简单)。
答案1
legend image code
您只需为此进行自己的设置即可。
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\pgfplotsset{/pgfplots/half and half legend/.style={
/pgfplots/legend image code/.code={%
\draw[##1,/tikz/.cd,densely dotted]
(0cm,0cm) -- (0.3cm,0cm);
\draw[##1,/tikz/.cd,solid]
(0.3cm,0cm) -- (0.6cm,0cm);},},
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[domain=0:10, no marks,half and half legend]
\addplot+[red, solid] {x - 1}; \label{one}
\addplot+[blue, solid] {2*x - 3}; \label{two}
\addlegendentry[red]{$m = 2$}
\addlegendentry[blue]{$m = 1$}
\addplot+[red, densely dotted] {x - 0}; \label{three}
\addplot+[blue, densely dotted] {2*x + 2}; \label{four}
\end{axis}
\end{tikzpicture}
\end{document}