【问题标题】:Creating a Stacked Percentage Bar Chart in R with ggplot使用 ggplot 在 R 中创建堆积百分比条形图
【发布时间】:2016-03-10 14:41:42
【问题描述】:

我一直在寻找一种方法,能够根据受访者的性别分类将堆积的条形图响应显示为百分比值。

我成功地创建了使用变量“性别”填充的堆积条形图,但我希望该图显示该变量之间的比例。我知道使用 (..count..)/sum(..count) 和 scale_y 可以更改 y 轴以显示百分比,但我找不到将它用于我想要的方法。手动使用频率值 [edit] 反映百分比的单独数据框也是可能的,但我真的很想寻找一种仅使用 ggplot 的方法。

This is what the plot currently looks like:

这是当前代码:

workday<-ggplot(student,aes(x=Dalc2,fill=sex))
plot1<-workday+geom_bar()+facet_wrap(~romantic2)+labs(title="Workday Alcohol Consumption",y="Number of Respondents",x="Response")+ylim(0,300)

我知道这是一个非常基本的问题,但任何对此问题的启发将不胜感激。

(来自 uci.edu 的数据集)

编辑:

对于那些对解决方案感兴趣的人,r.bot(非常感谢!)建议使用geom_bar(position="fill")

还添加这个来修改 y 轴: scale_y_continuous(labels=percent)

This is what the final graph looks like

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    ggplot online documentation 有一个很好的例子,将条形堆叠到 100%。由于您没有提供数据,我无法调整您的代码。例如,请参阅

    # http://docs.ggplot2.org/current/geom_bar.html
    require(ggplot2)
    
    g <- ggplot(mpg, aes(class))
    g + geom_bar(aes(fill = drv), position = "fill")
    

    position = "fill"应该可以得到你想要的。

    【讨论】:

    • 我不敢相信我在尝试寻找答案的几个小时后错过了那个。非常感谢,它就像一个魅力!
    猜你喜欢
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2015-01-16
    相关资源
    最近更新 更多