如何在 ggplot2 R 图中设置轴限制?
我绘制了以下内容:
library(ggplot2)
carrots <- data.frame(length = rnorm(500000, 10000, 10000))
cukes <- data.frame(length = rnorm(50000, 10000, 20000))
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'
vegLengths <- rbind(carrots, cukes)
ggplot(vegLengths, aes(length, fill = veg)) +
geom_density(alpha = 0.2)
现在说,我只想绘制 x=-5000
到 5000
之间的区域,而不是整个范围。
我怎样才能做到这一点?
I plot the following:
library(ggplot2)
carrots <- data.frame(length = rnorm(500000, 10000, 10000))
cukes <- data.frame(length = rnorm(50000, 10000, 20000))
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'
vegLengths <- rbind(carrots, cukes)
ggplot(vegLengths, aes(length, fill = veg)) +
geom_density(alpha = 0.2)
Now say, I only want to plot the region between x=-5000
to 5000
, instead of the entire range.
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,您有两个选项
,
第一个选项删除给定范围之外的所有数据点,第二个选项仅调整可见区域。在大多数情况下,您不会看到差异,但如果您对数据进行任何拟合,则可能会更改拟合值。
您还可以使用简写函数
xlim
(或ylim
),它与第一个选项一样会删除给定范围之外的数据点:有关详细信息,请检查
coord_cartesian
。ggplot2
的 RStudio 备忘单 使这一点在视觉上非常清晰。这是该备忘单的一小部分:根据 CC BY< 分发/a>。
Basically you have two options
or
Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.
You can also use the shorthand function
xlim
(orylim
), which like the first option removes data points outside of the given range:For more information check the description of
coord_cartesian
.The RStudio cheatsheet for
ggplot2
makes this quite clear visually. Here is a small section of that cheatsheet:Distributed under CC BY.
快速注意:如果您还使用
coord_flip()
翻转 x 轴和 y 轴,则无法使用coord_cartesian()
设置范围限制,因为这两个函数是互斥的(请参阅此处)。幸运的是,这是一个简单的修复方法。在
coord_flip()
内设置限制,如下所示:这只会改变可见范围(即不会删除数据点)。
Quick note: if you're also using
coord_flip()
to flip the x and the y axis, you won't be able to set range limits usingcoord_cartesian()
because those two functions are exclusive (see here).Fortunately, this is an easy fix; set your limits within
coord_flip()
like so:This just alters the visible range (i.e. doesn't remove data points).