从两个分类变量分组的条形图

时间:2017-06-26 08:23:35

标签: r bar-chart

我有两个分类变量:education.typework.type

education.type = c(1,1,2,1,2,2,1,1,2,2,1,2,1)
work.type = c(1,2,1,2,1,2,1,2,1,2,1,1,1)

1 ="技术" 2 ="非技术性"

我想有一个分组的条形图,如下所示:

enter image description here

感谢您的回复

2 个答案:

答案 0 :(得分:0)

我试过了:

education.type=c(1,1,2,1,2,2,1,1,2,2,1,2,1)
work.type=c(1,2,1,2,1,2,1,2,1,2,1,1,1)
tt =table(education.type, work.type)
tt
              work.type
education.type 1 2
             1 4 3
             2 4 2
barplot (tt,beside=TRUE)

tt表不合适,因此条形图是错误的。 所以我试过cbind。

cc = cbind(education.type, work.type)
cc
      education.type work.type
 [1,]              1         1
 [2,]              1         2
 [3,]              2         1
 [4,]              1         2
 [5,]              2         1
 [6,]              2         2
 [7,]              1         1
 [8,]              1         2
 [9,]              2         1
[10,]              2         2
[11,]              1         1
[12,]              2         1
[13,]              1         1

条形图为每个条目提供了一个条形

答案 1 :(得分:0)

education.type = c(1,1,2,1,2,2,1,1,2,2,1,2,1)
work.type = c(1,2,1,2,1,2,1,2,1,2,1,1,1)

te = sum(education.type == 1)
nte = sum(education.type == 2)

tw = sum(work.type == 1)
ntw = sum(work.type == 2)

education = rbind(te, nte)
work = rbind(tw, ntw)

df = as.data.frame(cbind(education, work))
rownames(df) = c("technical", "nontechnical")
colnames(df) = c("education", "work")
df$x = rownames(df)

library(reshape2)
mlt = melt(df, id.vars = "x")
mlt

ggplot(data=mlt, aes(x=x, y=value, fill=variable)) +
  geom_bar(stat="identity", color="black", position=position_dodge())

enter image description here