如何在ggplot2中防止坐标轴交叉

6
我正在使用ggplot2制作一些对数转换数据的折线图,这些数据都有很大的值(在10^6和10^8之间); 由于轴不从零开始,我希望它们不要在“原点”相交。以下是当前轴的外观: ggplot2 plot 我更喜欢从基本图形中得到的效果(但我还使用geom_ribbon和其他我在ggplot2中非常喜欢的花哨的东西,所以我更喜欢找到一个ggplot2解决方案): non-intersecting axes 以下是我目前正在做的事情:
mydata <- data.frame(Day = rep(1:8, 3), 
  Treatment = rep(c("A", "B", "C"), each=8), 
  Value = c(7.415929, 7.200486, 7.040555, 7.096490, 7.056413, 7.143981, 7.429724, 7.332760, 7.643673, 7.303994, 7.343151, 6.923636, 6.923478, 7.249170, 7.513370, 7.438630, 7.209895, 7.000063, 7.160154, 6.677734, 7.026307, 6.830495, 6.863329, 7.319219))

ggplot(mydata, aes(x=Day, y=Value, group=Treatment)) 
  + theme_classic() 
  + geom_line(aes(color = Treatment), size=1) 
  + scale_y_continuous(labels = math_format(10^.x)) 
  + coord_cartesian(ylim = c(6.4, 7.75), xlim=c(0.5, 8))

plot(mydata$Day, mydata$Value, frame.plot = F)  #non-intersecting axes

所以你想要类似底部图形的更多东西吗?你可以尝试使用geom_pointqplot? - Harpal
2个回答

3
解决此问题的方法是使用theme(axis.line=element_blank())删除轴线,然后使用geom_segment()添加虚假轴线 - 一个用于x轴,另一个用于y轴。 xyxendyend值从您的图表中确定(取相应轴上显示的最小值和最大值),并使用在coord_cartesian()中使用的轴限制(最小值)确保在轴的位置绘制线段。
ggplot(mydata, aes(x=Day, y=Value, group=Treatment)) +theme_classic() +
 geom_line(aes(color = Treatment), size=1) +
 scale_y_continuous(labels = math_format(10^.x))+ 
 coord_cartesian(ylim = c(6.4, 7.75), xlim=c(0.5, 8))+
 theme(axis.line=element_blank())+
 geom_segment(x=2,xend=8,y=6.4,yend=6.4)+
 geom_segment(x=0.5,xend=0.5,y=6.5,yend=7.75)

enter image description here


1
一个比较老的问题。但最近我也在寻找这个功能,所以我想提一下 ggh4x 包,它可以为 截断轴 添加指南线。
library(ggh4x)
#> Loading required package: ggplot2

ggplot(data.frame(x=0:10, y=0:10), aes(x, y)) +
  geom_point() +
  theme_classic() +
  guides(x = "axis_truncated", y = "axis_truncated")

本文档于2023年2月17日使用reprex v2.0.2创建

除了方便之外,ggh4x 选项还有两个好处:1)它在更复杂的图表组合(如分面)中稳定;2)它的依赖关系是属于 ggplot2 子集的,因此您不会引入大量额外的导入。

P.S. 有一个开放式 GitHub 问题(issue),旨在将这种“浮动坐标轴”功能引入到主要的 ggplot2 库中。看起来它最终会被合并。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接