首页 > 解决方案 > 如何统一ggplot2中条的宽度?

问题描述

我正在尝试使用 geom_bar(stat="count") 按性别获取条形图,除了条形的宽度不一致之外,一切似乎都很好。例如,如果“F”组中没有得分值为 3 的观察值,则“M”组的条形将变为两倍大。如何使其与示例中的其他条一样窄?

Score = read.table(header=TRUE,text='score sex
    1 0 F
    2 0 F
    3 0 M
    4 0 M
    5 0 F
    6 1 F
    7 1 M
    8 1 M
    9 2 F
    10 2 M
    11 2 F
    12 3 M
    13 3 M'
    )

b1=ggplot(Score, aes(x=factor(score), fill=sex))+
    geom_bar(stat="count", position=position_dodge())+
    theme_classic()
b1

标签: widthbar-chart

解决方案


将 position=position_dodge2(preserve="single") 添加到 geom_bar() 行解决了它:

b1=ggplot(Score, aes(x=factor(score), fill=factor(sex)))+
    geom_bar(stat="count", position=position_dodge2(preserve="single"))+
    theme_classic()
b1

推荐阅读