在堆积条形图中自动设置轴限制

在堆积条形图中自动设置轴限制

这是一个堆积条形图:

\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}

在此处输入图片描述

我已经进行了硬编码yminymax手动操作。如何动态地完成?

答案1

我找到了一个解决方案。我定义了两个函数,分别构成所有负值和所有正值的总和。然后它们对应于轴限值。

% !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}

相关内容