使用ggplot2的两组的Barplot

时间:2016-02-13 11:55:37

标签: r ggplot2 bar-chart

我知道以前曾多次询问过这个问题。但是,我无法找到解决问题的方法。

我通过假人扩展mtcars数据集,指示汽车卖家是买卖还是购买(买= 0 - >卖,买= 1 - >买)和日期事务:

data(mtcars)
mtcars$buy <- c(0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,1,1,0,0,0,1,0,1,0,1,1,0,0,0,1,0,1)
mtcars$date <- as.Date(c('2011-01-01','2011-01-06','2011-01-10','2011-01-20','2011-01-23',
             '2011-01-25','2011-01-31','2011-02-01','2011-02-06','2011-02-15',
             '2011-02-22','2011-02-26','2011-03-05','2011-03-15','2011-03-20',
             '2011-03-22','2011-03-27','2011-04-10','2011-04-25','2011-04-28',
             '2011-05-05','2011-05-15','2011-06-05','2011-06-06','2011-06-17',
             '2011-06-25','2011-07-05','2011-07-11','2011-07-25','2011-07-31',
             '2011-08-23','2011-08-25'))

现在我想使用ggplot来获得每月销售的条形图并以单独的条形式购买。但是,我只能创建所有交易的摘要图:

mtcars$month <- as.Date(cut(mtcars$date, breaks="month")) 
mtcars$counter <- 1
ggplot(mtcars, aes(month,counter)) + stat_summary(fun.y=sum, geom="Bar")

如何创建相同的图表,但每个月有两个条形图(一个有购买数量,另一个有销售数量)?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我认为购买向量需要是字符串而不是数字。

ggplot(mtcars, aes(month)) + geom_bar(aes(fill=as.character(buy)),position = "dodge")

enter image description here