14

I would like to make a graph of some points, where ymin is at most 0. By default, ymin is the value of the lowest point in the graph. I would like to let ymin be the value of the lowest point or 0 if all points are positive.

Here is an illustration of what I want to obtain (in both cases where the lowest point is negative and not negative). enter image description here

\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} 
6
  • Remark : I am using currently the workaround consisting of adding a point at (1,0) with opacity=0. But I guess that there is a smarter solution. Sep 11, 2013 at 19:32
  • 4
    pgfplotstable can be used to analyze data before plotting it, and set ymin accordingly.
    – alfC
    Sep 11, 2013 at 20:48
  • 1
    I like your solution myself. Sep 13, 2013 at 4:23
  • @Joseph Wright♦ Did I do the right thing here?
    – Symbol 1
    Jan 1, 2016 at 16:21
  • @Symbol1 Ah, I missed that one: should I dupe (or even merge)?
    – Joseph Wright
    Jan 1, 2016 at 16:43

1 Answer 1

11
+50

Here's a style that checks whether the current ymin of the plots encountered so far is greater than the maximum allowed ymin (in your case that would be 0) and then sets the axis limit accordingly. The style also sets enlarge y limits=upper when ymin is constrained:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.