使用ggplot在R中创建堆积的百分比条形图 [英] Creating a Stacked Percentage Bar Chart in R with ggplot
问题描述
我用填充的变量'sex'创建了一个堆积条形图,但我希望这个图表显示这个变量之间的比例。我知道使用(..count ..)/ sum(.. count)和scale_y可以更改y轴,以便显示百分比,但我找不到用于我想要的方式。手动做一个单独的数据框架与频率值反映百分比也是可能的,但我真的热衷于寻找一种方式来使用ggplot。
这是当前的代码:
workday< -ggplot(student,aes(x = Dalc2,fill =性别))
plot1< -workday + geom_bar()+ facet_wrap(〜romantic2)+ labs(title =工作日酒精消费量,y =受访者人数,x =回复)+ ylim(0,300 )
我知道这是一个非常基本的问题,但是对这个问题的任何启发都将不胜感激。 / p>
(来自uci.edu的数据集)
编辑:
对于那些对解决方案感兴趣的人,r.bot(非常感谢!)建议使用 geom_bar(position =fill)
另外添加这个来修改y轴:
scale_y_conti nuous(labels = percent)
://docs.ggplot2.org/current/geom_bar.htmlrel =noreferrer>在线文档有一个很好的例子,堆积的酒吧到100%。因为您没有提供数据,所以我无法调整您的代码。例如,请参阅
#http://docs.ggplot2.org/current/geom_bar.html
要求(ggplot2)
g< - ggplot(mpg,aes(class))
g + geom_bar(aes(fill = drv),position =fill)
I have been looking for a way to be able to show the stacked bar chart responses as percentage values, according to the gender classification of the respondents. I was successful in creating a stacked bar plot using the variable 'sex' for the fill, but I want the plot to show the proportion between this variable. I know that using (..count..)/sum(..count) and scale_y can change the y axis so that it shows the percentages, but I can't find a way to use it for what I want. Manually doing a separate data frame with the frequency values [edit] reflecting the percentages is also possible, but I am really keen on looking for a way to use only ggplot. This is what the plot currently looks like: This is the current code: I know it's a pretty basic problem, but any enlightenment on this one would be greatly appreciated. (Data set from uci.edu) EDIT: For those interested in the solution, r.bot (lots of thanks!) suggested using Also adding this to modify the y-axis:
This is what the final graph looks like The ggplot online documentation has a nice example of stacked bars to 100%. I can't adapt your code as you haven't provided the data. As an example, see The 这篇关于使用ggplot在R中创建堆积的百分比条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!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)
geom_bar(position="fill")
scale_y_continuous(labels=percent)
# 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"
should get you what you want.