我一直在浏览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"
可以使用以下命令创建:
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")
最后一行给出了以下情节:
我真正想要的是将一个组中的每个条形连接到一个单独的条形,并将百分比表示为相同条形的分数(每个组中的每个成员都用一个条形图绘制,每个条形条具有百分比作为他们的颜色)。所以我使用了以下内容:
ggplot(dat, aes(x=Member, y=Percentage)) + geom_bar(stat="identity", colour="white")
并获得了这个:
但是现在我无法正确地获得颜色。我想要的东西与下面给出的东西完全相同,但我无法理解如何做到这一点。有关如何做到这一点的任何建议吗?
答案 0 :(得分:11)
好吧终于搞定了!欢呼!如果其他人有兴趣,这是完整的代码:
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(非常感谢!)的建议:
ggplot(dat, aes(x=Member, y=Percentage, fill=Percentage)) + geom_bar(stat="identity", colour="white")
答案 1 :(得分:4)
你很亲密。尝试
ggplot(dat, aes(x=Member, y=Percentage, fill = factor(Percentage))) + geom_bar(stat = "identity")
哪个产生