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

ggplot2绘图问题:各州大选与州选举得票率柱状图无法并列

解决ggplot并列柱状图重叠问题

问题核心:你现在用两个单独的geom_bar()分别绘制大选和州选举的数据,ggplot无法将这两个系列识别为需要并列的分组,导致柱子重叠。正确的做法是先把宽格式数据转成长格式,再用单个geom_bar()通过fill映射分组变量来实现并列。

修正步骤:

  • 使用tidyr::pivot_longer()将数据从宽格式(两列得票率)转换为长格式(一列选举类型,一列得票率)
  • 单个geom_bar()中通过aes(fill = 选举类型)指定分组,配合position = "dodge"实现并列
  • 调整geom_text的position参数,确保标签和对应柱子对齐

完整修正代码:

library(ggplot2)
library(tidyr)

# 转换数据格式为长格式
BJP.voteshare.long <- pivot_longer(BJP.voteshare.2019,
                                   cols = c(voteshare.bjp.x, voteshare.bjp.y),
                                   names_to = "Election_Type",
                                   values_to = "Vote_Share")

# 替换选举类型的显示标签
BJP.voteshare.long$Election_Type <- factor(BJP.voteshare.long$Election_Type,
                                           levels = c("voteshare.bjp.x", "voteshare.bjp.y"),
                                           labels = c("州选举", "全国大选"))

# 绘制并列柱状图
ggplot(BJP.voteshare.long, aes(x = State_Name, y = Vote_Share, fill = Election_Type)) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.8)) +
  geom_text(aes(label = round(Vote_Share, 2)), 
            vjust = -0.5, size = 3, color = "black",
            position = position_dodge(width = 0.8)) +
  labs(title = "BJP得票率对比:州选举vs全国大选",
       x = "邦/州", y = "得票率(%)",
       fill = "选举类型") +
  scale_fill_manual(values = c("blue", "red")) +
  theme_minimal()

关键说明:

  • 转长格式后,所有得票率数据集中在一列,选举类型作为分组变量,ggplot能明确区分两组数据,position_dodge才能生效让柱子并列
  • position_dodge(width = 0.8)要在geom_bar和geom_text中保持一致,确保标签和柱子精准对齐
  • 用factor()重新定义选举类型的标签,让图例和图表内容更直观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:22:11