R 强制原点从0开始

R 强制原点从0开始,r,plot,ggplot2,axes,R,Plot,Ggplot2,Axes,如何在ggplot2中设置y轴和x轴的原点/截取 x轴的直线应正好位于y=Z 使用Z=0或其他给定值。xlim和ylim不要在此处剪切它。您需要使用expand\u limits、scale\u x\u continuous和scale\u y\u continuous。尝试: df <- data.frame(x = 1:5, y = 1:5) p <- ggplot(df, aes(x, y)) + geom_point() p <- p + expand_limits(x

如何在ggplot2中设置y轴和x轴的原点/截取

x轴的直线应正好位于
y=Z


使用
Z=0
或其他给定值。

xlim
ylim
不要在此处剪切它。您需要使用
expand\u limits
scale\u x\u continuous
scale\u y\u continuous
。尝试:

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for


您可能需要稍微调整一些以确保点不会被截断(例如,请参见
x=5
y=5
处的点,只需将这些点添加到ggplot中即可:

+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
例子
df在最新版本的ggplot2中,这可能更容易


p我还需要指定限制:
scale\u x\u continuous(expand=c(0,0),limits=c(0,5))
,不知何故,如果没有它,它就不起作用了。我认为多做一件会有帮助,这是使用类似于
expand=expand\u scale(mult=c(0,0.1))的东西
因此,您仍然可以在上端添加填充:是否也可以将其构建到新的ggplot主题中?@Bolle我不确定,但也有兴趣了解一下,您可以单独提问并链接到此处链接以供将来参考这只会更改数据点周围的填充,但无助于将轴原点设置为零或其他期望值。
+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for


p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))