我想使用 pgfplots 中的堆叠条形图来直观显示泰坦尼克号上头等舱、二等舱和三等舱的女性和男性乘客数量。
这里的代码:
\documentclass[crop,tikz]{standalone}
\usepackage{pgfplots}
\pgfplotsset{width=10cm,compat=1.9}
\usetikzlibrary{patterns}
\definecolor{acolor}{HTML}{D55E00}
\definecolor{bcolor}{HTML}{0072B2}
\begin{document}
\begin{tikzpicture}
\begin{axis}[ybar stacked,
bar width=2cm,
axis lines=left,
axis line style={opacity=0},
ytick=\empty,
major x tick style = transparent,
ymin=0, ymax=750,
enlarge x limits=0.2,
nodes near coords,
symbolic x coords={1st class, 2nd class, 3rd class},
xtick=data,
legend style={draw=none, at={(0.5,-0.1)},
anchor=north,legend columns=-1},]
\addplot+[ybar, fill=acolor, draw=none, text=white] plot coordinates {(1st class, 179)(2nd class, 172)(3rd class, 499)};
\addplot+[ybar, fill=bcolor, draw=none, text=white] plot coordinates {(1st class, 143)(2nd class, 107)(3rd class, 212)};
\legend{male passengers,female passengers}
\end{axis}
\end{tikzpicture}
\end{document}
但是,图例的边框显示不正确。我期望图例区域没有任何边框。如何解决这个问题?
答案1
你应该添加
\pgfplotsset{compat=1.18}
(或者您拥有的版本;否则,您正在运行启用的原始“错误”......)
然后添加选项
legend image post style={fill, draw=white},
在 之后legend style
。我认为这draw=none
应该有效,但它似乎被忽略了。(我在手册中的“所有支持的样式”中发现了它)。
答案2
用于legend image code
创建所需的图例图像。(此处为略低于基线的矩形)
图例方块没有边框(使用draw=none
)
\documentclass[12pt,a4paper]{article}
\usepackage{crop,tikz}
\usepackage{pgfplots}
\pgfplotsset{width=10cm,compat=1.18}
\usetikzlibrary{patterns}
\definecolor{acolor}{HTML}{D55E00}
\definecolor{bcolor}{HTML}{0072B2}
\begin{document}
\begin{tikzpicture}
\begin{axis}[ybar stacked,
bar width=2cm,
axis lines=left,
axis line style={opacity=0},
ytick=\empty,
major x tick style = transparent,
ymin=0, ymax=750,
enlarge x limits=0.2,
nodes near coords,
symbolic x coords={1st class, 2nd class, 3rd class},
xtick=data,
legend image code/.code={%
\draw[#1, draw=none] (0cm,-0.2cm) rectangle (0.4cm,0.2cm);
},
legend style={
% no rectangle around
draw=none, %
% position of the legend
at={(0.05,-0.2)},
anchor= west,
legend columns=-1,
/tikz/column 2/.style={column sep=15pt},
},
]
\addplot+[ybar, fill=acolor, draw=none, text=white] plot coordinates {(1st class, 179)(2nd class, 172)(3rd class, 499)};
\addplot+[ybar, fill=bcolor, draw=none, text=white] plot coordinates {(1st class, 143)(2nd class, 107)(3rd class, 212)};
\legend{male passengers,female passengers}
\end{axis}
\end{tikzpicture}
\end{document}