[Tex/LaTex] pgfplots: Multiple (shifted) stacked plots in one diagram

pgfplots

How can I get multiple stacked plots (ybar stacked, stack plots=y) in one diagram, such that there are multiple stacked bars for the same x-coordinate, each slightly shifted? Is there a way to reset pgfplot's zero levels after an \addplot command, such that the next \addplot[xhshift=...] doesn't add something to the current stack, but rather starts a fresh stack?

FWIW, overlaying two plots with scale only axis won't help; I need this to work with groupplot

Best Answer

I assume you want "stacked and clustered bar charts".

The following solution is not the most elegant, but it works quite well. It basically resets the stacked plot variables and starts stacking the following plots. I haven't found a way to properly reset the zero levels for the first plot after the reset command, that's why I use an invisible plot with the forget plot option that has zero values at all coordinates. This does not interrupt the style cycle, but unfortunately it requires hard coding the coordinates and won't work if you don't know the number of bar stacks beforehand.

Plenty of room for improvement, but it's a start and might be enough for you to get the job done.

\documentclass{article}
\usepackage{pgfplots}

\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,
    xtick=data,
    ymin=0,
    enlarge x limits=0.5,
    legend entries={A,B,C,D,E}
]
\addplot +[bar shift=-.2cm] coordinates {(1,1) (2,1.75) (3,0.5)};
\addplot +[bar shift=-.2cm] coordinates {(1,0.5) (2,2.5) (3,1.5)};

\resetstackedplots

\addplot  +[bar shift=.2cm]coordinates {(1,1.2) (2,1.5) (3,0.3)};
\addplot  +[bar shift=.2cm] coordinates {(1,0.5) (2,2) (3,1.5)};
\addplot  +[bar shift=.2cm] coordinates {(1,0.2) (2,0.1) (3,0.3)};
\end{axis}
\end{tikzpicture}
\end{document}

Related Question