如何在ggplot翻转坐标系的柱状图中添加多组Y轴文本?
问题:ggplot能否实现多文本系列的横向柱状图效果?
需求说明
- 当前绘图:横向渐变填充柱状图,仅展示类别名称与对应柱子
- 目标效果:在每个柱子的对应位置添加1-2组额外文本系列,实现类似多列信息对齐展示的横向条形图效果
当前绘图代码
ggplot() + geom_col(data = s, aes(x = V1, y = V3, fill = V3), show.legend = F) + coord_flip() + labs(x = "", y = "") + scale_fill_gradient(low = "yellow", high="darkgreen") + theme(axis.text.y = element_text(vjust = 0, hjust = 0), plot.margin = margin(1, 0.3, 0.1, 0.3, "cm"), panel.background = element_rect(fill = 'white', colour = 'white'), axis.ticks.y = element_blank()) + ylim(0, 6)
数据说明
模拟数据
1 a b 6 7 2 c d 8 9 3 g f 5 4 4 f n 3 2
真实数据结构
structure(list(V1 = c("regulation of locomotion", "regulation of cell migration", "skin development", "negative regulation of biological process", "cell adhesion", "response to oxygen-containing compound"), V2 = c(7.74e-05, 0.000143, 0.000165, 0.000176, 0.00019, 0.00019), V3 = c(4.111259039, 3.844663963, 3.782516056, 3.754487332, 3.721246399, 3.721246399 )), row.names = c(NA, 6L), class = "data.frame")
解决方案:完全可以用ggplot实现
核心思路是通过geom_text()在指定位置添加文本系列,结合坐标调整实现对齐。以下是基于真实数据的示例代码:
实现代码
library(ggplot2) # 加载真实数据 s <- structure(list(V1 = c("regulation of locomotion", "regulation of cell migration", "skin development", "negative regulation of biological process", "cell adhesion", "response to oxygen-containing compound"), V2 = c(7.74e-05, 0.000143, 0.000165, 0.000176, 0.00019, 0.00019), V3 = c(4.111259039, 3.844663963, 3.782516056, 3.754487332, 3.721246399, 3.721246399 )), row.names = c(NA, 6L), class = "data.frame") ggplot(s, aes(x = V1, y = V3)) + geom_col(aes(fill = V3), show.legend = F) + # 添加第一组文本(V2,格式化科学计数法) geom_text(aes(y = 6.2, label = sprintf("%.1e", V2)), hjust = 0, size = 3.5) + # 若需第二组文本,复制该行并调整y值即可 # geom_text(aes(y = 6.8, label = "自定义文本"), hjust = 0, size = 3.5) + coord_flip() + labs(x = "", y = "") + scale_fill_gradient(low = "yellow", high="darkgreen") + theme( axis.text.y = element_text(vjust = 0, hjust = 0), plot.margin = margin(1, 2, 0.1, 0.3, "cm"), # 加大右侧边距避免文本截断 panel.background = element_rect(fill = 'white', colour = 'white'), axis.ticks.y = element_blank() ) + ylim(0, 7) # 扩大y轴范围预留文本空间
关键要点
- 通过调整
geom_text()的y参数(coord_flip()后对应横向位置)控制文本的左右排列 - 多组文本通过多次调用
geom_text(),设置不同y值实现分层 - 若需要更复杂的文本样式(如背景、换行),可替换为
ggtext::geom_richtext()
内容的提问来源于stack exchange,提问作者Amir Valizadeh
相关产品推荐
相关产品推荐

