我在数据集中的列如下所示:
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] 删除。
我来说两句