如何获得虚拟变量的堆积条形图

用户名

我在数据集中的列如下所示:

teacher student  
 y        n  
 y        n  
 y        y  
 y        n  
 y        n  
 n        n  
 n        n   
 n        y  
 y        y  
 n        y  
 y        n  

我用了

barchart(data$teacher) 

对于教师图,它在两个单独的条形图中显示了y和n的频率,但是现在我想对两个变量显示y和n的堆叠,因此每个变量一个条形。我尝试了很多类似的操作,chart.StackedBar但是它们都没有用。谢谢你的帮助!

拉尔

编辑:根据您的评论,这是您要寻找的吗?

library(reshape2)
tmp <- melt(dat, id.vars = NULL)
names(tmp) <- c('Occupation', 'ID')

ggplot(data = tmp, aes(x = Occupation, fill= ID)) + geom_histogram()

在此处输入图片说明

原版的:

我已经使用来处理这种类型的图ggplot这是一个简单的示例:

library(ggplot2)
set.seed(1618)
dat <- data.frame(teacher = sample(c('y','n'),10,replace=T),
                  student = sample(c('y','n'),10,replace=T))

ggplot(data = dat, aes(x = teacher, fill = student)) + geom_histogram()

在此处输入图片说明

您可能还会考虑

ggplot(data = dat, aes(x = teacher, fill = student)) + 
geom_histogram(alpha= .5, position = 'identity')

看起来像:

在此处输入图片说明

如果您无法分辨,第二张图只是“叠加”了条形图,而不是将它们堆叠在一起。

我不太擅长ggplot,但希望能有所帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章