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

如何实现按党派配色、按结果设图案的堆叠条形图正确分组

问题描述

使用geom_col_pattern绘制条形图时,按party(党派)设置填充颜色,按二元变量consequence(取值0/1)设置填充图案,希望同一党派的两个consequence条形紧邻排列(如Party A(0)挨着Party A(1),接着是Party B(0)、Party B(1),以此类推),同时保留原有的配色和图案规则。

解决方案

核心是通过自定义有序分组变量,让ggplot按指定逻辑排列条形,结合position_dodge实现同党派的两个条形并排展示。

步骤1:创建有序分组变量

在数据中生成结合party和consequence的因子变量,手动指定水平顺序,确保同党派的两个consequence相邻:

df <- df %>%
  mutate(party_consequence = factor(
    paste(party, consequence, sep = "_"),
    levels = c("Party A_0", "Party A_1", "Party B_0", "Party B_1", "Party C_0", "Party C_1")
  ))

步骤2:修改绘图代码

将group参数设为新的分组变量,同时设置position = position_dodge(width = 0.8)实现条形并排,保留原有的填充色和图案映射:

ggplot(df, aes(x = year, y = n, fill = party, group = party_consequence)) +
  geom_col_pattern(
    aes(pattern = factor(consequence)),
    colour = "black",
    pattern_colour = "white",
    pattern_fill = "white",
    pattern_density = 0.3,
    pattern_spacing = 0.025,
    position = position_dodge(width = 0.8)  # 关键:实现同党派的两个条形并排
  ) +
  scale_fill_manual(values = party_colors) +
  scale_pattern_manual(values = c("0" = "none", "1" = "stripe")) +
  labs(
    x = "年份",
    y = "数量",
    fill = "党派",
    pattern = "结果"
  ) +
  theme_classic()

效果说明

修改后,每个年份下的条形会按Party A(0) → Party A(1) → Party B(0) → Party B(1) → Party C(0) → Party C(1)的顺序排列,同一党派的两个条形紧邻,同时保留了原有的党派配色和结果图案规则。

可选:分面展示(更清晰)

如果觉得同一年份下条形过多,可按年份分面,将x轴设为自定义分组变量:

ggplot(df, aes(x = party_consequence, y = n, fill = party)) +
  geom_col_pattern(
    aes(pattern = factor(consequence)),
    colour = "black",
    pattern_colour = "white",
    pattern_fill = "white",
    pattern_density = 0.3,
    pattern_spacing = 0.025
  ) +
  facet_wrap(~year, nrow = 1) +  # 按年份横向分面
  scale_fill_manual(values = party_colors) +
  scale_pattern_manual(values = c("0" = "none", "1" = "stripe")) +
  scale_x_discrete(
    labels = c(
      "Party A\n(无结果)", "Party A\n(有结果)",
      "Party B\n(无结果)", "Party B\n(有结果)",
      "Party C\n(无结果)", "Party C\n(有结果)"
    )
  ) +
  labs(
    x = "党派 & 结果",
    y = "数量",
    fill = "党派",
    pattern = "结果"
  ) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 15:05:04