ggplot2绘图求助:调整Y轴标签间距与文本居中
解决ggplot绘图的两个问题
问题1:缩小Y轴类别间距
将Y轴从连续型转为离散型,移除上下空白区域,同时缩小误差线高度,让元素更紧凑:
- 把
aes中的y = ID改为y = factor(ID),适配类别型数据 - 在
scale_y_discrete中添加expand = c(0, 0),消除Y轴上下的空白 - 调小
geom_errorbarh的height参数,减少误差线的纵向占用
问题2:多行标签居中对齐
使用ggtext包支持markdown/HTML格式的文本渲染,实现多行标签居中:
- 用
<br>替换换行符,并用<center>包裹标签内容 - 在
theme中设置axis.text.y = element_markdown(hjust = 0.5),确保文本居中
完整代码示例
# 安装并加载所需包(首次使用需安装ggtext) install.packages("ggtext") library(ggplot2) library(ggtext) # 你的原始数据 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") # 调整Y轴标签为居中的markdown格式 yaxis <- c( "<center>Ppppppppp ppppppp<br>pppp pp pppppp<br>(ppp)</center>", "<center>Uuuuuuuuu uuuuu</center>", "<center>Iiiiiii iiiii<br>ii Iiiiii (iiii)</center>" ) # 绘图代码 myplot <- 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轴,消除上下空白,设置标签 scale_y_discrete(breaks = 1:3, labels = yaxis, expand = c(0, 0)) + # 使用ggtext渲染居中标签 theme(axis.text.y = element_markdown(hjust = 0.5)) # 显示图形 myplot
无额外包替代方案(手动居中)
如果不想安装ggtext,可以用stringr::str_pad手动调整每行文本的缩进:
library(stringr) yaxis <- c( paste0(str_pad("Ppppppppp ppppppp", 20, "both"), "\n", str_pad("pppp pp pppppp", 20, "both"), "\n", str_pad("(ppp)", 20, "both")), str_pad("Uuuuuuuuu uuuuu", 20, "both"), paste0(str_pad("Iiiiiii iiiii", 20, "both"), "\n", str_pad("ii Iiiiii (iiii)", 20, "both")) ) myplot <- 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)) + scale_y_discrete(breaks = 1:3, labels = yaxis, expand = c(0, 0)) + theme(axis.text.y = element_text(hjust = 0.5))
内容的提问来源于stack exchange,提问作者Rustam
相关产品推荐
相关产品推荐

