简体   繁体   English

使用ggplot2的两组的Barplot

[英]Barplot for two groups using ggplot2

I know this has been asked many times before. 我知道这已经被问过很多次了。 However, I can't find the solution for my problem. 但是,我找不到解决问题的方法。

I extended the mtcars data set by a dummy indicating whether the car was sold or bought by a car seller (buy = 0 -> Sell, buy = 1 -> Buy) and the date of the transaction: 我通过一个虚拟人扩展了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'))

Now I want to use ggplot to get a barplot with the monthly sells and buys as separate bars. 现在,我想使用ggplot来获取带有每月销售量和购买量的条形图作为单独的条形图。 However, I can only create a summary plot of all transactions: 但是,我只能创建所有交易的摘要图:

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

How can I create the same graph, but with two bars for each month (one with the number of buys and the other with the number of sells)? 如何创建相同的图形,但每个月有两个条形图(一个带有购买数量,另一个带有出售数量)?

Thanks for your help! 谢谢你的帮助!

I believe the buy vector needs to be strings instead of numbers. 我认为购买向量必须是字符串而不是数字。

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM