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

ggplot2中实现不同分组下条形图等宽度的方法咨询

ggplot2中实现不同分组下条形图等宽度的方法咨询

嗨,这个问题我之前也碰到过!默认的position = "dodge"会根据每个Statut分组里实际存在的Code类别数量自动调整条形宽度,所以当某个Statut(比如你提到的“not yet started”)对应的Code更少时,条形就会变宽。要解决这个问题,有两个实用的方法:

  • 方法一:用position_dodge()的preserve参数强制统一宽度
    这是最直接的方案,把原来的position = "dodge"替换成position = position_dodge(preserve = "single"),这个参数会让所有分组的条形保持相同宽度,不管每个Statut下有多少个Code类别。不过要注意,如果你的数据里某些Statut + Code的组合不存在(也就是count为0),最好先补全这些缺失的行,不然对应的位置会留空,但宽度还是会保留。可以用tidyr::complete()来补全数据:

    先处理数据:

    library(tidyr)
    # 补全所有Statut和Code的组合,缺失的count设为0
    df_complete <- df_incoming %>%
      complete(Statut, Code, fill = list(count = 0))
    

    然后修改绘图代码:

    ggplot(data = df_complete, aes(x = Statut, fill = Code)) +
      geom_bar(position = position_dodge(preserve = "single"), aes(y = count), stat = "identity") +
      labs(x = "Statut", y = "Aantal") +
      scale_fill_manual(values = brewer.pal(12, "Set3")) +
      theme_minimal()
    

    这里要注意把geom_bar()的stat设为"identity",因为你已经用了y = count,默认的stat = "count"会重新计算计数,可能和你现有的count列冲突。

  • 方法二:用分面替代分组填充(可选)
    如果觉得第一种方法的布局不太满意,也可以把Code放到x轴,然后按Statut分面,这样每个分面里的条形宽度自然是一致的:

    ggplot(data = df_incoming, aes(x = Code, fill = Code)) +
      geom_bar(aes(y = count), stat = "identity") +
      facet_wrap(~Statut) +
      labs(x = "Code", y = "Aantal") +
      scale_fill_manual(values = brewer.pal(12, "Set3")) +
      theme_minimal()
    

    这个方法的好处是每个Statut的条形都独立展示,宽度完全一致,但布局会变成多面板的形式,你可以根据需求选择。

备注:内容来源于stack exchange,提问作者user21699241

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 07:18:07