简体   繁体   中英

Find the different value between each factor and plot the histogram in r

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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