如何在ggplot2 R图中设置轴限制? [英] How to set limits for axes in ggplot2 R plots?

查看:192
本文介绍了如何在ggplot2 R图中设置轴限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  library(ggplot2)

胡萝卜< - 数据。帧(长度= rnorm(500000,10000,10000))
cukes < - data.frame(长度= rnorm(50000,10000,20000))
胡萝卜$ veg < - '胡萝卜'
cukes $ veg < - 'cuke'
vegLengths < - rbind(carrots,cukes)

ggplot(vegLengths,aes(length,fill = veg))+
geom_density(alpha = 0.2)

现在说我只想绘制 x = -5000 5000 ,而不是整个范围。

我该怎么做?

解决方案

基本上你有两个选择:

< pre $ scale_x_continuous(limits = c(-5000,5000))

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

第一个删除给定范围之外的所有数据点,第二个仅调整可见区域REA。在大多数情况下,你不会看到差异,但是如果你适合任何数据,它可能会改变拟合值。



你也可以使用简写函数 xlim (或 ylim ),与第一个选项类似,它将删除给定范围之外的数据点:

  + xlim(-5000,5000)

有关更多信息,请查看



根据 CC BY 发布。


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?

解决方案

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:

Distributed under CC BY.

这篇关于如何在ggplot2 R图中设置轴限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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