ggplot在多个类别中绘制比例 [英] ggplot graphing proportions within multiple categories
问题描述
我试图为多个分组的数据绘制真/假比例。具体来说,我希望看到数据列c的真/假比例,它可以按照a和b的真/假数据分组。
<$ c (c(真(假),假,FALSE),50,replace = TRUE)
df = as.data.frame(cbind(a,b,c))
我试过这个:
ggplot(df,aes(x = a,fill = c))+
geom_bar(position =fill)
但是我没有知道如何将B中的真/假数据实现到图中。基本上我想要4c比例:A / B =假/假,假/真,真/假,真/真
http://i.stack.imgur.com/HhtHZ.png
这实际上是我想要的图表,除了time = A,sex = B和total_bill = c / true / false的比例。 >
这是一种使用 dplyr
的方法。
library(dplyr)
library(ggplot2)
set.seed(111)
a = sample(c(TRUE,FALSE),50,replace = TRUE)
b = sample(c(TRUE,FALSE),50,replace = TRUE)
c = sample(c(TRUE ,FALSE),50,replace = TRUE)
df = as.data.frame(cbind(a,b,c))
UPDATED
鉴于OP的评论,此处为修订版。
foo < - group_by(df,a,b,c)%>%
summary(total = n()) %>%
mutate(prop = total / sum(total))
#绘制一个ggplot数字
ggplot(foo,aes(x = a,y = fill = b))+
geom_bar(stat =identity,position =dodge)
I am trying to graph true/false proportions for data with multiple groupings. Specifically, I want to see the true/false proportions for data column c which can be grouped by true/false data from a and b.
a = sample(c(TRUE, FALSE), 50, replace=TRUE)
b = sample(c(TRUE, FALSE), 50, replace=TRUE)
c = sample(c(TRUE, FALSE), 50, replace=TRUE)
df = as.data.frame(cbind(a,b,c))
I tried this:
ggplot(df,aes(x = a, fill = c)) +
geom_bar(position = "fill")
But I don't know how to implement the true/false data from B into the graph. Essentially I want 4 c proportions: A/B = False/False, False/True, True/False, True/True
http://i.stack.imgur.com/HhtHZ.png
This is essentially the graph I want, except time=A, sex=B, and total_bill=proportion of true/false for c
Here is one approach using dplyr
.
library(dplyr)
library(ggplot2)
set.seed(111)
a = sample(c(TRUE, FALSE), 50, replace=TRUE)
b = sample(c(TRUE, FALSE), 50, replace=TRUE)
c = sample(c(TRUE, FALSE), 50, replace=TRUE)
df = as.data.frame(cbind(a,b,c))
UPDATED
Given the comments of the OP, here is a revised version.
foo <- group_by(df, a, b, c) %>%
summarise(total = n()) %>%
mutate(prop = total / sum(total))
# Draw a ggplot figure
ggplot(foo, aes(x = a, y = prop, fill = b)) +
geom_bar(stat = "identity", position = "dodge")
这篇关于ggplot在多个类别中绘制比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!