Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum y axis in ggplot2

Tags:

r

ggplot2

I have a simple data.frame:

exdataframe <- data.frame(
  date = c("2020-10-18","2020-10-20","2020-10-21","2020-10-31","2020-10-29","2020-11-01","2020-11-02"),
  Salesman = c("Bob","Mark","Rob","Rob", "Mark","Richard","Richard"),
  values = c(10,50,30,100,120,90,20)
)
exdataframe$date <- as.Date(exdataframe$date) # transform to Date class

So I plot:

ggplot(exdataframe, aes(x = cut(date, breaks = "month"), y = values, fill=Salesman)) + 
  geom_bar(stat = "identity",position=position_dodge()) +
  geom_text(aes(label=values), position=position_dodge(width=0.9), vjust=-0.25) + 
  xlab("Month")

enter image description here My question is how to sum all the Y axis values by Salesman column and group by month and by Salesman?

like image 964
RIckHenr Avatar asked Nov 01 '20 18:11

RIckHenr


1 Answers

We can do a group by sum

library(dplyr)
library(lubridate)
library(ggplot2)
library(zoo)
exdataframe %>%
    group_by(month = as.yearmon(date), Salesman) %>%
    summarise(values = sum(values), .groups = 'drop') %>%
    ggplot(aes(x = month, y = values, fill = Salesman, group = Salesman)) + 
     geom_bar(stat = 'identity', position = position_dodge())

-output

enter image description here

like image 141
akrun Avatar answered Nov 05 '22 07:11

akrun