您可以使用
stat_summary
具有
geom_smooth
:
library(ggplot2)
set.seed(47)
df <- data.frame(a = runif(100),
b = runif(100),
c = runif(100),
d = rnorm(2700),
dates = as.Date("2013-12-31") + 1:60)
df$Metric <- ifelse(df$a > 0.5, "a", "b")
df$Methodology <- factor(ifelse(df$a > 0.5, "One", "Two"))
ggplot(df, aes(x = dates, y = b)) +
geom_point() +
stat_smooth(size = 1.5) +
geom_smooth(stat = 'summary', alpha = 0.2, fill = 'red', color = 'red',
fun.data = median_hilow, fun.args = list(conf.int = 1)) +
scale_x_date(date_breaks = "1 week", date_labels = "%d-%b-%y") +
facet_wrap(~ Methodology + Metric, ncol = 1)
#> `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
自从
conf.int = 1
,这将在每个x值的最小值和最大值之间绘制一个功能区,中间值为直线。如果确实要绘制第25百分位和第75百分位,请设置
conf.int = 0.5
. 在这些数据上,没有足够的观测数据在每个x值处显示出非常不同的结果,但是,在一些新的样本数据上,
library(ggplot2)
set.seed(47)
ggplot(tibble::tibble(x = rep(seq(0, 4*pi, length.out = 50), 50),
y = rnorm(2500) * sin(x) + sin(x)),
aes(x, y)) +
geom_point(alpha = 0.1) +
geom_smooth(fill = 'darkblue') +
geom_smooth(stat = 'summary', color = 'red', fill = 'red', alpha = 0.2,
fun.data = median_hilow, fun.args = list(conf.int = 0.5))
#> `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
median_hilow
(真的
Hmisc::smedian.hilow
)但是,不允许设置分位数的类型,因此为了进行更精确的控制,请重写函数(返回结构类似的数据帧)或将每个统计信息的单独函数传递给
fun.y
,
fun.ymin
和
fun.ymax
参数。