在R语言ggplot2中如何修改柱状图的binwidth参数?
解决ggplot2中无法修改分箱宽度的问题
问题根源:你当前使用
geom_bar(stat="count")时,stat="count"的作用是统计每个独立x值的出现次数,不存在分箱逻辑,因此binwidth参数完全无效。两种可行解决方案:
- 直接使用
geom_histogram(推荐):它默认对连续型x变量执行分箱统计,直接添加binwidth参数即可控制分箱宽度:ggplot(missense2) + geom_histogram(aes(x = Variant.start.in.translation..aa.), binwidth = 2) + theme_classic() + xlab("amino acid position") - 保留
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
相关产品推荐
相关产品推荐

