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

在R语言ggplot2中如何修改柱状图的binwidth参数?

解决ggplot2中无法修改分箱宽度的问题
  • 问题根源:你当前使用geom_bar(stat="count")时,stat="count"的作用是统计每个独立x值的出现次数,不存在分箱逻辑,因此binwidth参数完全无效。

  • 两种可行解决方案:

    1. 直接使用geom_histogram(推荐):它默认对连续型x变量执行分箱统计,直接添加binwidth参数即可控制分箱宽度:
      ggplot(missense2) +
        geom_histogram(aes(x = Variant.start.in.translation..aa.), binwidth = 2) +
        theme_classic() +
        xlab("amino acid position")
      
    2. 保留geom_bar但修改统计方式:将stat参数改为"bin",同时指定binwidth:
      ggplot(missense2) +
        geom_bar(aes(x = Variant.start.in.translation..aa.), stat = "bin", binwidth = 2) +
        theme_classic() +
        xlab("amino acid position")
      
  • 额外注意:如果你的Variant.start.in.translation..aa.是离散型变量,需先转换为连续型(比如as.numeric(Variant.start.in.translation..aa.)),分箱才能正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:10:40