如何使用 ggplot 绘制堆叠条形图? [英] How do I plot a stacked bar with ggplot?

查看:99
本文介绍了如何使用 ggplot 绘制堆叠条形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在浏览这个页面上提供的示例,但出于某种原因无法找到正确的方法.

I have been going through the examples provided on this page, but for some reason unable to find the right way of doing this.

我有一些这样的数据:

      Group Member Percentage
 [1,] "1"   "A"    "60"      
 [2,] "1"   "A"    "20"      
 [3,] "1"   "A"    "20"      
 [4,] "1"   "B"    "80"      
 [5,] "1"   "B"    "5"       
 [6,] "1"   "B"    "5"       
 [7,] "1"   "B"    "5"       
 [8,] "2"   "C"    "50"      
 [9,] "2"   "C"    "50"      
[10,] "2"   "D"    "25"      
[11,] "2"   "D"    "25"      
[12,] "2"   "D"    "25"      
[13,] "2"   "D"    "20"      
[14,] "2"   "D"    "5"   

并且可以使用以下命令创建:

and can be created with the following commands:

a = c(1,1,1,1,1,1,1,2,2,2,2,2,2,2)
b = c("A","A","A","B","B","B","B","C","C","D","D","D","D","D")
c = c(60,20,20,80,5,5,5,50,50,25,25,25,20,5)
dat = data.frame(Group=a, Member=b, Percentage=c)
ggplot(dat, aes(x=Member, y=Percentage)) + geom_bar(stat="identity", position="dodge", fill="white", colour="black")

最后一行给了我以下情节:

The last line gives me the following plot:

我真正想要的是将一组中的每个条形连接到一个条形,并将百分比表示为同一条形的分数(其中每个组的每个成员都用一个条形绘制,每个条形具有百分比作为它们的颜色).所以我使用了以下内容:

What I am really looking for is to concatenate each of the bars in one group to one single bar and represent the percentages as fraction of the same bar (where each member from each group is plotted with one bar with each bar having the percentages as their colors). So I used the following:

ggplot(dat, aes(x=Member, y=Percentage)) + geom_bar(stat="identity", colour="white")

并获得了这个:

但现在我无法正确获取颜色.我想要一些与下面给出的完全相同的东西,但我无法理解如何做到这一点.有关如何执行此操作的任何建议?

But now I can't get the colors properly. I want something exactly like the one give below but I am not able to understand how to do this. Any suggestions on how to do this?

推荐答案

好的,终于搞定了!欢呼!如果有人感兴趣,这是完整的代码:

Ok finally got it! Hurray! Here's the complete code if someone else is interested:

a = c(1,1,1,1,1,1,1,2,2,2,2,2,2,2)
b = c("A","A","A","B","B","B","B","C","C","D","D","D","D","D")
c = c(60,20,20,80,5,5,5,50,50,25,25,25,20,5)
dat = data.frame(Group=a, Member=b, Percentage=c)
ggplot(dat, aes(x=Member, y=Percentage, fill=Percentage)) + geom_bar(stat="identity", colour="white")

以及@joran(非常感谢!)在评论中提出的建议:

and with what was suggested by @joran (Thanks a lot!) in the comments:

ggplot(dat, aes(x=Member, y=Percentage, fill=Percentage)) + geom_bar(stat="identity", colour="white")

这篇关于如何使用 ggplot 绘制堆叠条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆