让 ymin 最多为 0

让 ymin 最多为 0

我想制作一些点的图表,其中 ymin 最多为 0。默认情况下,ymin是图表中最低点的值。我想让 为ymin最低点的值,如果所有点都是正数,则为 0。

下面是我想要获得的结果的说明(两种情况下最低点都是负数和非负数)。 在此处输入图片描述

\documentclass{standalone}
\usepackage{pgfplots}


\begin{document}

\begin{tikzpicture}
\begin{axis}[xtick={1,2,3}]
\addplot coordinates {(1,-1)(2,-3)(3,-4)};
\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[xtick={1,2,3},ymin=0]
\addplot coordinates {(1,5)(2,3)(3,2)};
\end{axis}
\end{tikzpicture}

\end{document} 

答案1

这是一种样式,用于检查迄今为止遇到的图的当前值是否ymin大于允许的最大值ymin(在您的情况下为 0),然后相应地设置轴限制。该样式还设置enlarge y limits=upper何时ymin受到约束:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}

\makeatletter
\pgfplotsset{
    max ymin/.style={
        execute at begin axis={
            \def\pgfplots@usedmaxymin{0}
        },
        execute at end plot={
            \pgfmathfloatparsenumber{#1}
            \edef\pgfplots@maxymin{\pgfmathresult}
            \pgfmathfloatgreaterthan{\pgfplots@ymin}{\pgfplots@maxymin}
            \ifdim\pgfmathresult pt=1pt
                \xdef\pgfplots@ymin{\pgfplots@maxymin}
                \xdef\pgfplots@usedmaxymin{1}
            \fi
        }
    },
    before end axis/.code={
        \if1\pgfplots@usedmaxymin
            \pgfplotsset{enlarge y limits=upper}
        \fi 
    }
}
\makeatother

\begin{document}
\makeatletter
\begin{tikzpicture}
\begin{axis}[
    max ymin=0
]
\addplot coordinates {(1,-1)(2,-3)(3,-4)};
\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[
    max ymin=0
]
\addplot coordinates {(1,5)(2,3)(3,2)};

\end{axis}
\end{tikzpicture}


\end{document} 

相关内容