You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

水平分组条形图:如何缩小组间间距与调整数值标签位置?

水平分组条形图优化:标签对齐与组间距调整

我正在为大学作业制作水平分组条形图,目前遇到两个问题:

  1. 无法缩小不同组(A、B、C、D、E、F)之间的条形间距
  2. 显示条形数值的标签位置不正确,调整位置参数无效

原代码

df <- data.frame(Category = c("A","B", "C", "D", "E", "F"), 
                 Student = c(4.4,3.35,5.96,2.07,4.56,3.55), 
                 Teacher = c(3.21,4.39,5.3,1.8,2.8,3.14))

data.m <- melt(df, id.vars='Category')

#Grouped Bar plot by Person#####

p <- ggplot(data.m, aes(x= reorder(Category, value), y= value)) + 
  geom_bar(aes(fill = variable), width = 0.30, position = position_dodge(width=0.3), stat="identity") +  
  geom_text(aes(label = value), hjust = -0.2, size = 2.5)

p <- p + labs(title = "Students and Teachers")

p <- p + labs(x = "Category", y = "Means")

p <- p + theme_classic()

p <- p + scale_y_continuous(expand=c(0,0))


p <- p + theme(legend.title = element_blank())

p <- p  + scale_fill_brewer(palette="Blues") 

p +  coord_flip() 

当前图表效果

当前水平分组条形图效果


一、搞定数值标签对齐

你的标签错位是因为geom_text没跟geom_bar用一样的position_dodge参数,导致两个标签堆在一起了。改这两点就行:

  • 给geom_text加上position = position_dodge(width = 0.3),和geom_bar里的position_dodge宽度保持一致,这样每个组的Student和Teacher标签会分别对应自己的条形
  • 因为用了coord_flip()翻转了坐标轴,原来的y轴(数值)变成了x轴,x轴(分类)变成了y轴,所以调整hjust控制标签位置:比如hjust = -0.1能让标签稍微靠右,刚好贴在条形末端外侧;如果想更贴近就用hjust = 0.1

修改后的geom_text行:

geom_text(aes(label = value), position = position_dodge(width = 0.3), hjust = -0.1, size = 2.5)

二、缩小组之间的间距

要让A、B、C这些组挨得更近,得调整离散坐标轴的扩展间距:

  • 因为coord_flip()之后,原来的分类x轴变成了y轴,所以用scale_y_discrete(expand = c(0, 0.1)),第二个参数越小,组之间的空隙就越小(你可以自己调0.05或者0.2,看实际效果)
  • 如果没翻转坐标轴的话,就对应使用scale_x_discrete(expand = c(0, 0.1))

完整修改后的代码

df <- data.frame(Category = c("A","B", "C", "D", "E", "F"), 
                 Student = c(4.4,3.35,5.96,2.07,4.56,3.55), 
                 Teacher = c(3.21,4.39,5.3,1.8,2.8,3.14))

data.m <- melt(df, id.vars='Category')

p <- ggplot(data.m, aes(x= reorder(Category, value), y= value)) + 
  geom_bar(aes(fill = variable), width = 0.30, position = position_dodge(width=0.3), stat="identity") +  
  # 调整标签位置与对齐
  geom_text(aes(label = value), position = position_dodge(width = 0.3), hjust = -0.1, size = 2.5) +
  labs(title = "Students and Teachers", x = "Category", y = "Means") +
  theme_classic() +
  scale_y_continuous(expand=c(0,0)) +
  theme(legend.title = element_blank()) +
  scale_fill_brewer(palette="Blues") +
  coord_flip() +
  # 缩小组间距
  scale_y_discrete(expand = c(0, 0.1))

p

内容的提问来源于stack exchange,提问作者minervax29

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 07:23:11