在下面的图中,如何将标题的红线分成一条红线和一条蓝色虚线(使得红蓝段的总长度与绿段的总长度相同)?
梅威瑟:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot [green,domain=-1:1] {x};
\legend{$f_1$}
\addplot [red,domain=-1:0] {x^3};
\addplot [blue,domain=0:1] {x^2};
\addlegendimage{blue}
\addlegendentry{$f_2$}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
一种可能性是使用legend image code/.code
和\addlegendimage
提供默认line legend
样式所需的变化:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend entries={$f_1$,$f_2$},]
\addlegendimage{no markers,green}
\addplot [green,domain=-1:1,forget plot] {x};
\addplot [red,domain=-1:0,forget plot] {x^3};
\addplot [blue,dashed,domain=0:1,forget plot] {x^2};
\addlegendimage{legend image code/.code={
\draw[red] plot coordinates {(0cm,0cm) (0.3cm,0cm)};
\draw[blue,dashed] plot coordinates {(0.3cm,0cm) (0.6cm,0cm)};
}
}
\end{axis}
\end{tikzpicture}
\end{document}
手册第 210 页pgfplots
有线条图例样式的定义:
\pgfplotsset{
/pgfplots/line legend/.style={
legend image code/.code={
\draw[mark repeat=2,mark phase=2,##1]
plot coordinates {
(0cm,0cm)
(0.3cm,0cm)
(0.6cm,0cm)
};%
}
}
}
所以该线的长度为0.6cm
。