我想使用 pgfplots 创建图表。我不喜欢 ybars 使用的图例符号,因此决定改用线图例条目和方块。我该如何填充这些标记,使它们具有与我的条形相同的颜色?
谢谢
\documentclass{article}
\usepackage{caption}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{tikz}
\begin{document}
\begin{figure}
\begin{tikzpicture}
\begin{axis}
[ybar,
xtick=data,
width=6cm,
height=5cm,
ymin=0,
ymax=0.7,
xmin=0.5,
xmax=6.5,
axis y line=left,
axis x line*=bottom,
xtick= {1,2,3,4,5,6},
bar width=4pt,
ytick={0,.1,.2,...,.7}
]
\addlegendimage{line legend,only marks,mark = square,color = black, fill =white}
\addlegendimage{line legend,only marks,mark = square,color = black, fill =gray}
\addlegendimage{line legend,only marks,mark = square,color = black, fill =black}
\addplot[xshift = 6pt,legend image post style={xshift=-6pt},color=black, fill =white, error bars, y dir=plus, y explicit]
coordinates{
(1,0.076844808) +- (1,0.043434089)
(2,0.282802471) +-(2,0.143136578)};
\addplot[xshift = -3pt,legend image post style={xshift=3pt},color=black,fill= gray, error bars, y dir = plus, y explicit]
coordinates{
(3,0.026724427) +-(3,0.019038655)
(4,0.061169214) +-(4,0.024462018)
(5,0.249852624) +-(5,0.047167041)
(6,0.064414295) +-(6,0.045149736)};
\addplot[xshift = -3pt,legend image post style={xshift=3pt},color=black, fill = black, error bars, y dir=plus, y explicit]
coordinates{
(3,0.082127485) +- (3,0.045713902)
(4,0.045611378) +- (4,0.018401772)
(5,0.299014506) +- (5,0.044026995)
(6,0.253207511) +- (6,0.320369411)
};
\legend{no, g/m, s}
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}
答案1
您可以使用legend image code/.code
键来定义如何绘制图例图像。对于您的情况,您可以执行以下操作:
legend image code/.code={%
\draw[#1] (0cm,0cm) rectangle (0.15cm,0.15cm);
}
\documentclass{article}
\usepackage{caption}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{tikz}
\begin{document}
\begin{figure}
\begin{tikzpicture}
\begin{axis}
[ybar,
xtick=data,
width=6cm,
height=5cm,
ymin=0,
ymax=0.7,
xmin=0.5,
xmax=6.5,
axis y line=left,
axis x line*=bottom,
xtick= {1,2,3,4,5,6},
bar width=4pt,
ytick={0,.1,.2,...,.7},
legend image code/.code={%
\draw[#1] (0cm,0cm) rectangle (0.15cm,0.15cm);
}
]
\addplot[xshift = 6pt,legend image post style={xshift=-6pt},color=black, fill =white, error bars, y dir=plus, y explicit]
coordinates{
(1,0.076844808) +- (1,0.043434089)
(2,0.282802471) +-(2,0.143136578)};
\addplot[xshift = -3pt,legend image post style={xshift=3pt},color=black,fill= gray, error bars, y dir = plus, y explicit]
coordinates{
(3,0.026724427) +-(3,0.019038655)
(4,0.061169214) +-(4,0.024462018)
(5,0.249852624) +-(5,0.047167041)
(6,0.064414295) +-(6,0.045149736)};
\addplot[xshift = -3pt,legend image post style={xshift=3pt},color=black, fill = black, error bars, y dir=plus, y explicit]
coordinates{
(3,0.082127485) +- (3,0.045713902)
(4,0.045611378) +- (4,0.018401772)
(5,0.299014506) +- (5,0.044026995)
(6,0.253207511) +- (6,0.320369411)
};
\legend{no, g/m, s}
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}