如何在ggplot2 R图中精确设置轴的极限? [英] How can I set exactly the limits for axes in ggplot2 R plots?

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

问题描述

使用ggplot绘制图,我希望精确设置我的轴.我知道我可以使用 coord_cartesian()设置绘图范围(例如,为我指定的x轴限制从2到4),但是在左侧和右侧留出一些空间我指定的范围的右侧:

Making a plot with ggplot, I wish to set my axis exactly. I am aware that I can set the plot range (e.g. for the x-axis I specified limits from 2 to 4) with coord_cartesian() but that leaves a bit of space to the left and right of the range I specify:

上面的MWE的代码:

library(ggplot2)

data.mwe = cbind.data.frame(x = 1:5, y = 2:6)

plot.mwe = ggplot(data = data.mwe, aes(x=x,y=y)) + geom_line() + coord_cartesian(xlim = c(2,4))
print(plot.mwe)

我想要的结果是绘制一个图,其中显示的区域恰好在我指定的限制之间.

My desired result is a plot where the displayed area is exactly between the limits I specify.

我知道如何在ggplot2 R图中设置轴的限制?但这并不能回答我的问题,因为它会在上面产生不希望的结果,或者削减观察结果(使用 scale_x_continuous limits 参数).我知道我可以修改一个较小的限制范围,但是我正在寻找一个干净的结果.至少我想知道实际范围与我指定的范围相差多少,以便我可以相应地调整自己的限制.

I am aware of How to set limits for axes in ggplot2 R plots? but it does not answer my question, as it produces the undesired result above, or cuts out observations (with the limits argument to scale_x_continuous). I know I could tinker with setting a smaller range for limits, but I am looking for a clean result. At the least I would like to know by how much the actual range differs from the one I specify, so that I could adapt my limits accordingly.

推荐答案

添加 expand = FALSE :

library(ggplot2)

data.mwe = data.frame(x = 1:5, 
                      y = 2:6)

ggplot(data.mwe, aes(x, y)) + 
    geom_line() + 
    coord_cartesian(xlim = c(2, 4), 
                    expand = FALSE)

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

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