如何在 ggplot2 R 图中设置轴限制?

发布于 2024-09-16 11:31:15 字数 441 浏览 2 评论 0原文

我绘制了以下内容:

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=-50005000 之间的区域,而不是整个范围。

我怎样才能做到这一点?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寂寞陪衬 2024-09-23 11:31:15

基本上,您有两个选项

scale_x_continuous(limits = c(-5000, 5000))

coord_cartesian(xlim = c(-5000, 5000)) 

第一个选项删除给定范围之外的所有数据点,第二个选项仅调整可见区域。在大多数情况下,您不会看到差异,但如果您对数据进行任何拟合,则可能会更改拟合值。

您还可以使用简写函数 xlim (或 ylim),它与第一个选项一样会删除给定范围之外的数据点:

+ xlim(-5000, 5000)

有关详细信息,请检查 coord_cartesian

ggplot2RStudio 备忘单 使这一点在视觉上非常清晰。这是该备忘单的一小部分:

在此处输入图像描述

根据 CC BY< 分发/a>

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000))

or

coord_cartesian(xlim = c(-5000, 5000)) 

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 (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000)

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:

enter image description here

Distributed under CC BY.

╰つ倒转 2024-09-23 11:31:15

快速注意:如果您还使用 coord_flip() 翻转 x 轴和 y 轴,则无法使用 coord_cartesian() 设置范围限制,因为这两个函数是互斥的(请参阅此处)。

幸运的是,这是一个简单的修复方法。在 coord_flip() 内设置限制,如下所示:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

这只会改变可见范围(即不会删除数据点)。

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 using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

This just alters the visible range (i.e. doesn't remove data points).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文