问题
node
我创建了一个图形,在其中绘制了一条线,并通过在命令中使用 s在线的开头添加一个节点,在线的结尾添加一个菱形,\addplot
如下所示:
\addplot[red,no markers,] {x} node[pos=0,circle,fill=red,inner sep=2pt,] {} node[pos=1,diamond,fill=red,inner sep=2pt,] {};
我想知道是否有办法在图例中也包含一条类似这样的线。
我知道我可以使用\addlegendimage
来生成自定义图例项,我也知道我可以使用\addlegendimage{red,->}
来生成一个红色箭头的自定义图例项,但我不知道如何创建一个图例项,它是一条线,开头有一个实心圆,结尾有一个实心菱形。以下方法不起作用,所以这就是我被卡住的地方:
\addlegendimage{\draw[red,] (0,0) node[circle,fill=red,inner sep=2pt,] {} -- (1,0) node[circle,fill=red,inner sep=2pt,] {};}
平均能量损失
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usepackage{tikz}
\usetikzlibrary{shapes}
\pgfplotsset{compat=1.10}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
legend entries={A,B,C,D},
legend pos=north west,
]
\addlegendimage{only marks,mark=*}
\addlegendimage{only marks,mark=diamond*}
\addlegendimage{no markers,red}
\addlegendimage{red,->}
\addplot[red,no markers,] {x} node[pos=0,circle,fill=red,inner sep=2pt,] {} node[pos=1,diamond,fill=red,inner sep=2pt,] {};
\end{axis}
\end{tikzpicture}
\end{document}
输出
答案1
您可以定义新的图例图像样式:
\pgfplotsset{
/pgfplots/line legend with two nodes/.style 2 args={
legend image code/.code={
\draw[##1,no markers]
plot coordinates {
(0cm,0cm)
(0.3cm,0cm)
(0.6cm,0cm)
}
node[pos=0,#1]{}
node[#2]{};%
}
}
}
代码:
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}% loads also tikz
\usetikzlibrary{shapes}
\pgfplotsset{compat=1.10}% current version is 1.13
\pgfplotsset{
/pgfplots/line legend with two nodes/.style 2 args={
legend image code/.code={
\draw[##1,no markers]
plot coordinates {
(0cm,0cm)
(0.3cm,0cm)
(0.6cm,0cm)
}
node[pos=0,#1]{}
node[#2]{};%
}
}
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
legend entries={A,B,C,D},
legend pos=north west,
]
\addlegendimage{only marks,mark=*}
\addlegendimage{only marks,mark=diamond*}
\addlegendimage{no markers,red}
\addlegendimage{
line legend with two nodes={circle,fill,inner sep=1pt}{diamond,fill,inner sep=1pt},
red}
\addplot[red,no markers,] {x}
node[pos=0,circle,fill=red,inner sep=2pt,] {}
node[diamond,fill=red,inner sep=2pt,] {};
\end{axis}
\end{tikzpicture}
\end{document}