只为 ggplot 设置限制的下界

是否可能只设置连续尺度极限的下界?我想使我的所有图0为基础,而不需要指定的上限界。

例如:。

+ scale_y_continuous(minlim=0)
47306 次浏览

I don't think you can do this directly. But as a work-around, you can mimic the way that ggplot2 determines the upper limit:

scale_y_continuous(limits=c(0, max(mydata$y) * 1.1))

How about using aes(ymin=0), as in:

ggplot(mtcars, aes(wt, mpg)) + geom_point() + aes(ymin=0)

You can use expand_limits

ggplot(mtcars, aes(wt, mpg)) + geom_point() + expand_limits(y=0)

Here is a comparison of the two:

  • without expand_limits

  • with expand_limits

As of version 1.0.0 of ggplot2, you can specify only one limit and have the other be as it would be normally determined by setting that second limit to NA. This approach will allow for both expansion and truncation of the axis range.

ggplot(mtcars, aes(wt, mpg)) + geom_point() +
scale_y_continuous(limits = c(0, NA))

specifying it via ylim(c(0, NA)) gives an identical figure.

You can also try the following code which will give you the min y-axis at zero and also without the extra gap between x-axis and min y value.

scale_y_continuous(limits = c(0, NA), expand = c(0,0))