如何在ggplot2中让y轴上的线条彼此靠近且贴近x轴
调整Y轴标签间距并贴近X轴的解决方案
问题背景
使用给定数据集和ggplot代码绘制横向误差棒图时,需要实现两个需求:
- Y轴上的三个标签彼此更紧凑
- 标签整体贴近X轴
此前使用scale_y_discrete(labels = yaxis, expand = expansion(add = 2))的方案会增大标签与X轴的距离,不符合当前需求。
数据集
df <- structure(list(vec = c("PC", "DEFAULT", "INFORMED"), mean = c(1.34944359241928, 1.36249329506777, 1.34671188869646), sd = c(0.57779881866326, 0.537279303541924, 1.53585580464849), min = c(0.196903771571785, 0.28781509871908, -1.66860228474139), `0.5quant` = c(1.35295469982876, 1.36643973099316, 1.34687516700723), max = c(2.48177705326348, 2.41483607230639, 4.36109982194179), mode = c(NA_real_, NA_real_, NA_real_), kld = c(1.9807860333589e-08, 2.97333113261951e-08, 3.91753938449056e-10), ID = 1:3), row.names = c(NA, -3L), class = "data.frame")
原绘图代码
yaxis <- c( "Ppppppppp ppppppp pppp pp pppppp (ppp)", "Uuuuuuuuu uuuuu","Iiiiiii iiiii ii Iiiiii (iiii)") ggplot(data = df, aes(x = mean, y = factor(ID))) + geom_point() + geom_errorbarh(aes(xmin = min, xmax = max), height = .1) + geom_vline(xintercept = 0, linetype = 2) + scale_x_continuous(breaks = seq(-4, 4.5, 0.5)) + scale_y_discrete(labels = yaxis) + theme(axis.text.y = element_text(hjust = .5))
解决方案
通过调整scale_y_discrete的expand参数,同时可选微调误差棒高度,实现标签紧凑且贴近X轴的效果:
ggplot(data = df, aes(x = mean, y = factor(ID))) + geom_point() + # 可选:缩小误差棒高度增强紧凑感 geom_errorbarh(aes(xmin = min, xmax = max), height = 0.05) + geom_vline(xintercept = 0, linetype = 2) + scale_x_continuous(breaks = seq(-4, 4.5, 0.5)) + # 调整Y轴扩展空间:底部负值贴近X轴,顶部少量扩展避免标签截断 scale_y_discrete(labels = yaxis, expand = expansion(add = c(-0.3, 0.1))) + theme(axis.text.y = element_text(hjust = .5))
参数说明
expand = expansion(add = c(-0.3, 0.1)):add参数的两个值分别对应Y轴底部(靠近X轴)和顶部的扩展空间。负值会减少底部空白,让标签更贴近X轴;顶部保留少量正值避免最上方标签被截断。height = 0.05:缩小误差棒的高度,让整体布局更紧凑,可根据需求调整数值。
如果需要进一步微调整体边距,可添加plot.margin参数:
+ theme( axis.text.y = element_text(hjust = .5), plot.margin = margin(t = 10, r = 10, b = 10, l = 10, unit = "pt") )
内容的提问来源于stack exchange,提问作者Rustam
相关产品推荐
相关产品推荐

