找到每个因素之间的不同值并在 r 中绘制直方图
Find the different value between each factor and plot the histogram in r
我正在学习 r,我想根据每个因素的变化构建直方图,具体取决于我数据框中的日期。
这是我的数据框:
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)
)
我的目标是找到例如:因子 Breakfast
我想像 13.5 - 12.75
,25.5 - 13.5
,27.4 - 25.5
一样得到它的革命,我想要同样的对于 Lunch
、Dinner
,然后使用这些差异值通过在 3 个不同的图形中使用 ggplot
进行绘图。
如有任何帮助,我们将不胜感激。谢谢!!!
我们根据差异创建分组
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)
-输出
我正在学习 r,我想根据每个因素的变化构建直方图,具体取决于我数据框中的日期。
这是我的数据框:
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)
)
我的目标是找到例如:因子 Breakfast
我想像 13.5 - 12.75
,25.5 - 13.5
,27.4 - 25.5
一样得到它的革命,我想要同样的对于 Lunch
、Dinner
,然后使用这些差异值通过在 3 个不同的图形中使用 ggplot
进行绘图。
如有任何帮助,我们将不胜感激。谢谢!!!
我们根据差异创建分组
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)
-输出