0

This is a stacked bar plot:

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.13}
\begin{document}
    \begin{tikzpicture}
        \begin{axis}[
            ybar stacked,
            bar width=\textwidth,
            axis line style={draw=none},
            xtick=\empty,
            xlabel={},
            ymin=-5.3,
            ymax=4.5,
            ]
            \addplot+[ybar, fill=blue, draw=none] plot coordinates {(0,1.5)};
            \addplot+[ybar, fill=red, draw=none] plot coordinates {(0,2)};
            \addplot+[ybar, fill=green, draw=none] plot coordinates {(0,-3)};
            \addplot+[ybar, fill=orange, draw=none] plot coordinates {(0,1)};
            \addplot+[ybar, fill=yellow, draw=none] plot coordinates {(0,-2.3)};
        \end{axis}
    \end{tikzpicture}
\end{document}

enter image description here

I have hardcoded ymin and ymax manually. How can that be done dynamically?

1 Answer 1

0

I found a solution. I have defined two functions that respectively form the sum of all negative, and all positive values. These then correspond to the axis limits.

% !TeX program = lualatex
\documentclass{article}
\usepackage{pgfplots}
\usepackage{luacode}
\pgfplotsset{compat=1.13}

\begin{luacode*}
    function sumpos(...)
    local sum = 0
    local values = {...}
    for _, value in ipairs(values) do
    if value > 0 then
    sum = sum + value
    end
    end
    tex.sprint(sum)
    end
\end{luacode*}
\begin{luacode*}
    function sumneg(...)
    local sum = 0
    local values = {...}
    for _, value in ipairs(values) do
    if value < 0 then
    sum = sum + value
    end
    end
    tex.sprint(sum)
    end
\end{luacode*}

\begin{document}
    
    \newcommand{\ypos}{\directlua{sumpos(1.5,2,-3,1,-2.3)}}
    \newcommand{\yneg}{\directlua{sumneg(1.5,2,-3,1,-2.3)}}
    
    \begin{tikzpicture}
        \begin{axis}[
            ybar stacked,
            bar width=\textwidth,
            axis line style={draw=none},
            xtick=\empty,
            xlabel={},
            ymin=\yneg,
            ymax=\ypos,
            ]
            \addplot+[ybar, fill=blue, draw=none] plot coordinates {(0,1.5)};
            \addplot+[ybar, fill=red, draw=none] plot coordinates {(0,2)};
            \addplot+[ybar, fill=green, draw=none] plot coordinates {(0,-3)};
            \addplot+[ybar, fill=orange, draw=none] plot coordinates {(0,1)};
            \addplot+[ybar, fill=yellow, draw=none] plot coordinates {(0,-2.3)};
        \end{axis}
    \end{tikzpicture}
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .