ggplot设置ylim最小或最大 [英] ggplot set ylim min OR max

查看:379
本文介绍了ggplot设置ylim最小或最大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图绘制一个图,在其中我可以指定y轴的最小值或最大值.但是我得到Error in if (zero_range(range)) { : missing value where TRUE/FALSE needed

I am trying to make a plot where I could just specify the min or the max value for the y axis. But I get Error in if (zero_range(range)) { : missing value where TRUE/FALSE needed

文档:

您可以保留一个值NA,以便根据数据范围进行计算.

You can leave one value as NA to compute from the range of the data.

因此,我做到了:

#Getting some data in
plot <- ggplot(mydata, 
               aes_string(y="yvar", x="xvar", colour="group", group="group", fill="group")
              )
#Adding some error bars
plot <- plot + geom_errorbar(aes(ymax=agg+var, ymin=agg-var), size=0.5, colour="black", data=mydata)

plot <- plot + geom_point(size=4) 
plot <- plot + geom_line(size=1)

#Here is when I just want to set y max
plot <- plot + coord_cartesian(ylim= c(NA, 100))

如果删除ylim或将NA更改为数字值,则效果很好.我在这里想念什么?

If I remove the ylim or change the NA to a numeric value, it works well. What am I missing here?

推荐答案

您可以使用扩展限制仅在一个方向上扩展轴.例如:

You can use expand limits to extend the axis in only one direction. For example:

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  expand_limits(y=c(NA, 50))

以您的示例为例,

plot + expand_limits(y=c(NA, 100))

您甚至可以提供一个值.如果该值大于数据的最大值,它将扩大最大值.如果低于数据的最小值,它将扩大最小值.在您的示例中:

You can even provide a single value. If that value is greater than the maximum of the data, it will expand the maximum. If lower than the minimum of the data, it will expand the minimum. In your example:

plot + expand_limits(y=100)

这是两个可重现的示例:

And here are two reproducible examples:

p = ggplot(mtcars, aes(wt, mpg)) +
  geom_point()

p + expand_limits(y=-20)
p + expand_limits(y=200)

这篇关于ggplot设置ylim最小或最大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆