ggplot坐标轴与数据标签对齐问题及变量顺序疑问
问题与解决方案
参考ggplot示例改写R代码后遇到两个问题:
- 绘图中的变量顺序与数据框中的顺序不一致
- 如何让数据标签位于绘图左右边缘,或至少完全对齐
原代码如下:
col <- c("Low weight", "very low weight", "Extra Very Low weight", "Cesarean section", "premature") ORpos <- c(6.8, 4.5,0.4, 4.5, 3.9) CI1 <- c(0.6, 0.4, 0, 0.2, 0.4) CI2 <- c(74, 56, 32, 20, 2.4) ORneg <- c(4.8, 15, 6, 6, 4) CI3 <- c(0.6, 0.4, 0, 0.2, 0.4) CI4 <- c(56, 43, 21, 10, 5) md4 <- data.frame(col,ORpos, CI1, CI2, ORneg, CI3, CI4) plot3 <- ggplot(md4, aes(x = col)) + geom_col( aes(y = Orp, fill = 'Orp')) +geom_text(aes(y=Orp, label = paste(Orp, " [", CI1," ; ", CI2, "]", sep = ""), hjust = -1))+ geom_col( aes(y = -Orn, fill = 'Orn')) + geom_text(aes(y=-Orn, label = paste(Orn, " [", CI3," ; ", CI4, "]", sep = ""), hjust = 1))+ coord_flip() + scale_y_continuous(limits = c(-30, 30)) plot3
问题1:变量顺序不一致的解决方法
ggplot默认会将字符型的x轴变量按字母顺序排序,要保持数据框中的原始顺序,需要将col列转换为因子类型,并指定levels为原数据框的顺序:
# 将col转换为因子,保留原始顺序 md4$col <- factor(md4$col, levels = md4$col)
问题2:数据标签对齐/固定到边缘的解决方法
首先修正原代码中的变量名错误:Orp应为ORpos,Orn应为ORneg,否则代码会报错。
要让标签固定到绘图边缘,可利用coord_flip()后轴的映射关系(原x轴变为y轴,原y轴变为x轴),直接指定标签的x坐标为轴的极限值,并配合hjust实现对齐:
- 对于右侧(ORpos)的标签,设置
x = 30(对应scale_y的上限),hjust = 0(左对齐,让文本紧贴边缘) - 对于左侧(ORneg)的标签,设置
x = -30(对应scale_y的下限),hjust = 1(右对齐,让文本紧贴边缘)
同时可以用nudge_y微调标签与柱子的间距,避免重叠。
修改后的完整代码:
library(ggplot2) col <- c("Low weight", "very low weight", "Extra Very Low weight", "Cesarean section", "premature") ORpos <- c(6.8, 4.5,0.4, 4.5, 3.9) CI1 <- c(0.6, 0.4, 0, 0.2, 0.4) CI2 <- c(74, 56, 32, 20, 2.4) ORneg <- c(4.8, 15, 6, 6, 4) CI3 <- c(0.6, 0.4, 0, 0.2, 0.4) CI4 <- c(56, 43, 21, 10, 5) md4 <- data.frame(col,ORpos, CI1, CI2, ORneg, CI3, CI4) # 转换为因子,保留原始顺序 md4$col <- factor(md4$col, levels = md4$col) plot3 <- ggplot(md4, aes(x = col)) + # 绘制正方向柱子 geom_col(aes(y = ORpos, fill = 'ORpos')) + # 右侧标签:固定到x=30位置,左对齐 geom_text(aes(y = ORpos, x = 30, label = paste(ORpos, " [", CI1," ; ", CI2, "]", sep = "")), hjust = 0, nudge_y = 0.5) + # 绘制负方向柱子 geom_col(aes(y = -ORneg, fill = 'ORneg')) + # 左侧标签:固定到x=-30位置,右对齐 geom_text(aes(y = -ORneg, x = -30, label = paste(ORneg, " [", CI3," ; ", CI4, "]", sep = "")), hjust = 1, nudge_y = -0.5) + coord_flip() + scale_y_continuous(limits = c(-30, 30)) + # 可选:修改填充色标签 labs(fill = "OR类型") plot3
补充说明:
如果不需要完全固定到边缘,只想让标签对齐,可保留原y轴位置,调整hjust并统一nudge_x(翻转后对应原y轴的微调),示例代码如下:
# 右侧标签:hjust=0,向右微调 geom_text(aes(y = ORpos, label = paste(ORpos, " [", CI1," ; ", CI2, "]", sep = "")), hjust = 0, nudge_x = 0.2) + # 左侧标签:hjust=1,向左微调 geom_text(aes(y = -ORneg, label = paste(ORneg, " [", CI3," ; ", CI4, "]", sep = "")), hjust = 1, nudge_x = -0.2)
内容的提问来源于stack exchange,提问作者LLA
相关产品推荐
相关产品推荐

