我如何确保图例中穿过棕色方块的线(更清晰,在 R^2 处)是绿色,就像图表的直线一样?
这是我的最小工作示例:
\documentclass[12pt]{article}
\usepackage{pgfplots}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
\begin{axis}[
legend pos=outer north east,
legend cell align={left},
grid,
grid style={line width=.1pt, draw=gray!0},
ymin=0,ymax=14,
xmax=14,xmin=0,
xtick={2,4,6,8,10,12},
ytick={2,4,6,8,10,12},
extra x ticks={0},
extra y ticks={0},
width=7cm,
height=7cm,
axis lines = middle,
set layers,
x label style={at={(1,0)},right},
y label style={at={(0,1)},above},
style={thick}
]
\addplot [green,smooth,thick,domain=0:12] {1.0016*x};
\addlegendentry{$f(x) = 1.0016x$};
\addplot[mark=square*,brown] coordinates {(0.1384,0.1338)};
\addplot[mark=square*,brown] coordinates {(1.288,1.278)};
\addplot[mark=square*,brown] coordinates {(11.65,11.67)};
\addlegendentry{$R^2 = 1.000$};
\end{axis};
\end{tikzpicture}
\end{figure}
\end{document}
答案1
一种选择是提前单独提供图例条目和相应的图像,使用图表开头的legend entries
轴选项和命令列表。这样您就可以分别指定线条颜色和标记颜色。\addlegendimage
梅威瑟:
\documentclass[12pt]{article}
\usepackage{pgfplots}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
\begin{axis}[
legend pos=outer north east,
legend cell align={left},
grid,
grid style={line width=.1pt, draw=gray!0},
ymin=0,ymax=14,
xmax=14,xmin=0,
xtick={2,4,6,8,10,12},
ytick={2,4,6,8,10,12},
extra x ticks={0},
extra y ticks={0},
width=7cm,
height=7cm,
axis lines = middle,
set layers,
x label style={at={(1,0)},right},
y label style={at={(0,1)},above},
style={thick},
legend entries={$f(x) = 1.0016x$, $R^2 = 1.000$}
]
\addlegendimage{no markers, green, thick}
\addlegendimage{green, thick, mark=square*, mark options={solid,draw=brown,fill=brown}}
\addplot [green,smooth,thick,domain=0:12] {1.0016*x};
\addplot[mark=square*,brown] coordinates {(0.1384,0.1338)};
\addplot[mark=square*,brown] coordinates {(1.288,1.278)};
\addplot[mark=square*,brown] coordinates {(11.65,11.67)};
\end{axis};
\end{tikzpicture}
\end{figure}
\end{document}
结果:
请注意,从概念上讲,在图例中添加 R² 框而不添加线可能更正确。这可以使用您的原始代码来完成,但only marks
在命令中指定\addplot
:
\addplot[only marks, mark=square*,brown] coordinates {(0.1384,0.1338)};
\addplot[only marks, mark=square*,brown] coordinates {(1.288,1.278)};
\addplot[only marks, mark=square*,brown] coordinates {(11.65,11.67)};
\addlegendentry{$R^2 = 1.000$};
这也允许您一次提供所有坐标,而无需在它们之间画一条线:
\addplot[only marks, mark=square*,brown] coordinates {(0.1384,0.1338) (1.288,1.278) (11.65,11.67)};