叼花硬汉 2010-08-31 07:03 采纳率: 0%
浏览 1606
已采纳

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

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?

转载于:https://stackoverflow.com/questions/3606697/how-to-set-limits-for-axes-in-ggplot2-r-plots

  • 写回答

2条回答 默认 最新

  • 零零乙 2010-08-31 07:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器