[英]How to plot smoothed summary stats in ggplot2
我在阐明这个问题时遇到了麻烦。 我有几年的每日收入和支出的数据集。 我一直在尝试一些方法,所以现在有很多日期列。
> str(df)
'data.frame': 3047 obs. of 8 variables:
$ Date : Factor w/ 1219 levels "2014-05-06T00:00:00.0000000",..: 6 9 2 3 4 6 10 11 13 14 ...
$ YearMonthnumber : Factor w/ 44 levels "2014/05","2014/06",..: 1 1 1 1 1 1 1 1 1 1 ...
$ cat : Factor w/ 10 levels "Account Adjustment",..: 1 2 3 3 3 3 3 3 3 3 ...
$ Value : num 2.2 277.7 20 14.1 6.8 ...
$ Income_or_expense: Factor w/ 2 levels "Expense","Income": 1 1 1 1 1 1 1 1 1 1 ...
$ ddate : Date, format: "2014-05-16" "2014-05-19" "2014-05-12" "2014-05-13" ...
$ monthly : Date, format: "2014-05-01" "2014-05-01" "2014-05-01" "2014-05-01" ...
基本上我要绘制的是:
我可以执行第一步,但是不能执行第二步。 这是我所拥有的:
ggplot(data = subset(df, cat!="Transfer"), aes(x = monthly, y= Value, colour = Income_or_expense)) +
stat_summary(fun.y = sum, geom = "point") +
scale_x_date(labels = date_format("%Y-%m"))
如何为这些生成的摘要统计信息添加平滑的几何图形?
编辑:如果我添加+ stat_summary(fun.y = sum, geom = "smooth")
,结果是折线图,而不是平滑模型。 如果我不带fun.y = sum
添加,则平滑线基于每日值,而不是每月总计
谢谢。
您可以先geom_smooth
汇总数据,然后对汇总的数据运行geom_smooth
。 我为该示例创建了一些虚假的时间序列数据。
library(tidyverse)
library(lubridate)
# Fake data
set.seed(2)
dat = data.frame(value = c(arima.sim(list(order = c(1,1,0), ar = 0.7), n = 364),
arima.sim(list(order = c(1,1,0), ar = 0.7), n = 364)) + 100,
IE = rep(c("Income","Expense"), each=365),
date = rep(seq(as.Date("2015-01-01"), as.Date("2015-12-31"), by="day"), 2))
现在我们按月求和并绘图。 我提供了实际每月总金额的积分,以便与更平滑的线进行比较:
ggplot(dat %>% group_by(IE, month=month(date, label=TRUE)) %>%
summarise(value=sum(value)),
aes(month, value, colour=IE, group=IE)) +
geom_smooth(se=FALSE, span=0.75) + # span=0.75 is the default
geom_point() +
expand_limits(y=0) +
theme_classic()
我对时间序列分析不太熟悉,但是似乎更好的方法是计算每个每日价值所表示的月收入和费用率,然后对其进行平滑处理。 这样,您就不会汇总基础数据中的变化。 在下面的图中,我包括了各个点,因此您可以将它们与更平滑的线进行比较。
ggplot(dat %>% group_by(IE, month=month(date, label=TRUE)) %>%
mutate(value = value * n()),
aes(date, value, colour=IE)) +
geom_smooth(se=FALSE, span=0.75) +
geom_point(alpha=0.3, size=1) +
expand_limits(y=0) +
theme_classic()
您还可以绘制30天的滚动总和,从而避免将数据分为任意时间段。 再次,我列出了每个每日价值代表的每月收入和费用率的积分。
library(xts)
ggplot(dat %>% group_by(IE) %>%
mutate(rolling_sum = rollsum(value, k=30, align="center", na.pad=TRUE),
value = value * 30),
aes(date, colour=IE)) +
geom_line(aes(y=rolling_sum), size=1) +
geom_point(aes(y=value), alpha=0.2, size=1) +
expand_limits(y=0) +
theme_classic()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.