jeffrey
jeffrey

Reputation: 2096

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:

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. 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!

Upvotes: 1

Views: 233

Answers (1)

Stephen Ingram
Stephen Ingram

Reputation: 190

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")

enter image description here

Upvotes: 1

Related Questions