我想为 3 个图创建一个简单的分组堆叠条形图。这是我的代码:
\documentclass[tikz,border=5mm]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}[
every axis/.style={
ybar stacked,
legend pos=north west, ymin=0, ymax = 10,
bar width=3pt,
x tick label style={rotate=45,anchor=east}
}
]
\begin{axis}[bar shift=-9pt, legend style = {name = serieA}]
\addplot [fill=blue] coordinates {
(1,2)
(2,3)};
\addlegendentry{$a$}
\end{axis}
\begin{axis}[bar shift=-6pt, hide axis, legend style = {at = {([xshift=0.5mm, yshift = 2.9mm]serieA)}}]
\addplot [fill=orange] coordinates {
(1,4)
(2,5)};
\addlegendentry{$b$}
\end{axis}
\begin{axis}[bar shift=-3pt, hide axis, legend style = {at = {([xshift=10mm, yshift = 2.9mm]serieA)}}]
\addplot [fill=green] coordinates {
(1,6)
(2,7)};
\addlegendentry{$c$}
\end{axis}
\end{tikzpicture}
\end{document}
结果是:
如您所见,有三个图例 a、b、c,它们彼此分开。我希望只有一个图例包含所有这三个图例。
答案1
- 这不是堆叠图...
- 你的代码可以简化
- 对于数据使用
pgfplotstable
包
\documentclass[border=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\usepackage{pgfplotstable}
\begin{document}
\begin{tikzpicture}
\pgfplotstableread{
X a b c
1 2 4 6
2 3 5 7
}\mydata
\begin{axis}[
ybar=0.4mm, % distance between bars (shift bar)
bar width=4mm, % width of bars
ymin=0, ymax=10,
%
xtick=data,
xticklabels from table = {\mydata}{X},
enlarge x limits = 0.4,
%
legend style = {legend columns=-1,
legend pos=north west,
font=\footnotesize,
/tikz/every even column/.append style={column sep=2mm},
},
]
\addplot table[x expr=\coordindex,y index=1] {\mydata};
\addplot table[x expr=\coordindex,y index=2] {\mydata};
\addplot table[x expr=\coordindex,y index=3] {\mydata};
\legend{$a$, $b$, $c$}
\end{axis}
\end{tikzpicture}
\end{document}
答案2
在这里,我根据这里提供的解决方案改编了这个答案:pgfplots:一个图表中的多个(移位)堆叠图
梅威瑟:
\documentclass[tikz,border=5mm]{standalone}
\usepackage{pgfplots}
% from https://tex.stackexchange.com/questions/13627/pgfplots-multiple-shifted-stacked-plots-in-one-diagram
\makeatletter
\newcommand\resetstackedplots{
\makeatletter
\pgfplots@stacked@isfirstplottrue
\makeatother
\addplot [forget plot,draw=none] coordinates{(1,0) (2,0) (3,0)};
}
\makeatother
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar stacked,
legend pos=north west, ymin=0, ymax = 10,
bar width=3pt,
xmax = 2.1,
x tick label style={rotate=45,anchor=east},
legend entries = {a,b,c},
]
\addplot [fill=blue, bar shift=-9pt] coordinates {
(1,2)
(2,3)};
\resetstackedplots
\addplot [fill=orange, bar shift=-6pt] coordinates {
(1,4)
(2,5)};
\resetstackedplots
\addplot [fill=green, bar shift=-3pt] coordinates {
(1,6)
(2,7)};
\resetstackedplots
\end{axis}
\end{tikzpicture}
\end{document}