r - ggplot2强制y轴从原点开始并 float y轴上限

标签 r ggplot2

经过一番搜索,我仍然不开心!

有没有简单的方法可以制作从原点开始并清晰显示所有数据的y轴图形?

这是我的问题:

set.seed(123)
my.data<- data.frame(x.var = rnorm(100, 50),
                     y.var = rnorm(100, 50,10))


## Annoying because it doesn't start at origin
ggplot(my.data, aes(x.var, y.var))+
  geom_point()


## Annoying because origin is not at bottom
ggplot(my.data, aes(x.var, y.var))+
  geom_point()+
  expand_limits(y = 0)

## Annoying because point is cut off
ggplot(my.data, aes(x.var, y.var))+
  geom_point()+
  scale_y_continuous(expand = c(0,0))+
  expand_limits(y = 0)

问题“在ggplot2(R)中强制原点从0开始”的最高答案是

“您可能需要稍作调整,以确保不会切断点数”

为什么会这样?我可以手动调整轴,但我不想每次都这样做!

互联网上的一些家伙有一个解决方案,涉及
#Find the current ymax value for upper bound
#(via http://stackoverflow.com/questions/7705345/how-can-i-extract-plot-axes-ranges-for-a-ggplot2-object#comment24184444_8167461 )
gy=ggplot_build(g)$panel$ranges[[1]]$y.range[2]
g=g+ylim(0,gy)

#Handle the overflow by expanding the x-axis
g=g+scale_x_continuous(expand=c(0.1,0))

对于我来说,这似乎很复杂,是一个相对简单的想法。我想念什么吗?

谢谢!

编辑:从2018年夏季开始,ggplot更新使上述修复不再起作用。当前(2018年8月),要从图中获取y-max,您现在需要执行以下操作。

gy=ggplot_build(g)$layout$panel_scales_y[[1]]$range$range[[2]]

最佳答案

我发现此问题令人沮丧,然后阅读R帮助文件中的expansion()。为此,有一个很好的ggplot选项,它是多面友好的,动态的和简洁的。

引用帮助文件:

mult
vector of multiplicative range expansion factors. If length 1, both the lower and upper limits of the scale are expanded outwards by mult. If length 2, the lower limit is expanded by mult[1] and the upper limit by mult[2].



请注意,add也是具有类似结构的选项。我会像这样解决这个问题:

ggplot(my.data, aes(x.var, y.var))+
  geom_point()+
  scale_y_continuous(limits = c(0, NA),
                     expand = expansion(mult = c(0, 0.1)))

首选此方法的一个重要原因是,如果您的几何图形具有不同的美学效果(例如,点和误差线),并且其刻面具有自由刻度...您仍然可以利用ggplot的巧妙的默认y轴行为,但可以强制x与y相交在每个面板中为0,仍然看到最上面的数据点。

关于r - ggplot2强制y轴从原点开始并 float y轴上限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27028825/

相关文章:

r - 为什么我在 R 中的 glmer 模型需要这么长时间才能运行?

r - 使用ggsave时遇到 "Error: $ operator is invalid for atomic vectors"

r - 使用 ggplot 绘制时间序列中多个变量的平均值

r - stat_sum 和 stat_identity 给出奇怪的结果

r - 如何使用 POSIXct 强制执行月初刻度标签?

r - ggplot2中没有数据时换行

r - 如何从R中的Excel文件中提取工作表名称

r - ggplot2:分面图上的着色轴文本

r - ggplot map 的奇怪内存问题

sql - 使用 RODBC 插入到 MS-Access 数据库中的备注字段时“无法分配内存”