从频率产生堆积的条形图

时间:2016-04-15 12:31:29

标签: r bar-chart

我有一个这样的数据框:

head(mydata)
id GeoBefore GeoAfter
1          A        A
2          B        B
3          A        B
4          B        A
5          A        A
6          B        B

我想绘制一个带有两列的堆积条形图,GerBefore和GeoAfter,我想显示每个栏中有多少A,B等......

我正在尝试:

gb <- cbind(mydata$GeoBefore, "2014")
ga <- cbind(mydata$GeoAfter, "2015")
geo <- as.data.frame(rbind(gb,ga))
colnames(geo) <- c("value", "period")
head(geo)
barplot(geo,
   legend.text=geo$period,
   args.legend=list(bty="n",horiz=TRUE),
   col=brewer.pal(5,"Set1"),border="white",
   main="Title")

但得到:

Error in barplot.default(geo, legend.text = geo$period, args.legend = list(bty = "n",  : 
'height' must be a vector or matrix

2 个答案:

答案 0 :(得分:0)

未测试

library(ggplot2)
ggplot(geo, aes(x = period, fill = value)) +
  geom_histogram()

答案 1 :(得分:0)

您可以通过以下方式执行此操作:

ans <- cbind(table(mydata$GeoBefore),table(mydata$GeoAfter))

colnames(ans) <- c("GeoBefore","GeoAfter")

barplot(ans,legend.text = rownames(ans))

enter image description here