2010-08-31 07:03 阅读 95

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

I plot the following:


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?


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    csdnceshi64 游.程 2010-08-31 07:15

    Basically you have two options

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


    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.

    点赞 22 评论 复制链接分享
  • csdnceshi67 bug^君 2016-09-02 18:43

    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).

    点赞 7 评论 复制链接分享