仅设置ggplot的限制下限

96

是否可能仅设置连续比例的下限而不设定上限? 我想使所有的图表都以0为基准,而无需指定上限。

例如:

+ scale_y_continuous(minlim=0)
5个回答

142
你可以使用 expand_limits
ggplot(mtcars, aes(wt, mpg)) + geom_point() + expand_limits(y=0)

下面是两种图形的比较:

  • 未使用expand_limits

  • 使用expand_limits

ggplot2版本1.0.0开始,您可以只指定一个限制,并使另一个限制像通常设置的那样成为NA。这种方法将允许轴范围的扩展和截断。

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


@PatrickT 你是不是想在 https://dev59.com/tF8d5IYBdhLWcg3wQwW5 下留言? - Brian Diggs
正是我所需要的。谢谢。 - Veera

11

可以尝试使用aes(ymin=0),就像这样:

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

7
这将覆盖 geom_errorbar 等的 ymin;使用 expand_limits() 更为安全。 - Mark
这并不是普适的,例如对于“geom_density”,它会给出“Error: stat_bin() must not be used with a y aesthetic”的错误提示,或者当放置在“geom_density”内部时,“Warning: Ignoring unknown aesthetics: ymin”(后者完全是预期的)。 - PatrickT
aes(ymin=o) 不会设置垂直轴的最小值。这并不是对问题的回答。 - randy

9
您也可以尝试以下代码,它将为您提供最小y轴为零且没有x轴和最小y值之间的额外间隙。
scale_y_continuous(limits = c(0, NA), expand = c(0,0))

2
有没有办法改用 coord_cartesian() 来实现这个功能? - randy

0

如果您想保持 ggplot 默认计算的比例尺的上限“不变”,并且消除下限的填充,使绘图区域从精确的0开始,那么在ggplot2 v3.0.0+中,您可以为比例尺的上限和下限指定单独的扩展值。

scale_y_continuous(limits = c(0, NA), expand = expansion(mult=c(0, 0.05)))

请参阅 help 中对于 scale_continuous() 的限制和扩展参数的描述。

使用方便的函数 expansion() 生成扩展参数的值。连续变量的默认值是在每个侧面扩展5%,离散变量的默认值是在每个侧面扩展0.6个单位。

我们使用 mult 参数来计算5%的扩展。

示例

ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  labs(subtitle="default")

default plot

ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  scale_y_continuous(limits=c(0, NA))+
  labs(subtitle="specifying limits alone leaves default 5% padding on both ends")

limits-alone

ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  scale_y_continuous(limits=c(0, NA), expand=expansion(mult=c(0, 0.05))) +
  labs(subtitle = "limits and an unequal expansion gets what we're after")

limits-and-expansion


-1

我认为你不能直接这样做。但是,作为一种解决方法,你可以模仿ggplot2确定上限的方式:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接