I am learning r and I want to build the histograms base on the revolution of each factor depend on the date in my dataframe.
Here is my dataframe:
dat <- data.frame(
time = factor(c("Breakfast","Breakfast","Breakfast","Breakfast","Lunch","Lunch","Lunch","Lunch","Dinner","Dinner","Dinner","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
date=c("2020-01-20","2020-01-21","2020-01-22","2020-01-23","2020-01-20","2020-01-21","2020-01-22","2020-01-23","2020-01-20","2020-01-21","2020-01-22","2020-01-23"),
total_bill = c(12.75,13.5,25.5,27.4,18.3,19.9,27.8,28.6,15.7,17.4,19.5,24.2)
)
My goal is to find for example: factor Breakfast
I want to get the revolution of it like 13.5 - 12.75
,25.5 - 13.5
,27.4 - 25.5
and I want the same for Lunch
, Dinner
and then used those difference values to plot by using ggplot
in 3 different graphs.
Any help for this would be much appreciated. Thank you!!!
We create do a group by difference
library(dplyr)
library(lubridate)
library(ggplot2)
dat %>%
mutate(date = ymd(date)) %>%
arrange(time, date) %>%
group_by(time) %>%
mutate(Diff = c(0, diff(total_bill))) %>%
ungroup %>%
filter(Diff != 0) %>%
ggplot(aes(x = date, y = Diff, fill = time)) +
geom_col()+
facet_wrap(~ time)
-output