1

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!

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.