我使用以下示例数据和代码
# Example
x1<- as.Date("2013-12-31")
adddate1 <- 1:60
dts <- x1 + adddate1
df <- data.frame(a=runif(100),b=runif(100),c=runif(100) ,d=rnorm(2700), dates=dts)
df$Metric <- ifelse(df$a > 0.5,"a", "b")
df$Methodology <- ifelse(df$a > 0.5,"One", "Two")
df$Methodology <- factor(df$Methodology)
pl<-df %>%
group_by(Methodology) %>%
do(
plots = ggplot(data=., aes(x = dates, y = b)) +
geom_point() +
stat_smooth(method="auto",size=1.5) +
stat_summary(fun.data=median_hilow, fun.args=(conf.int=1)) + # Show IQR
scale_x_date(date_breaks = "1 week", date_labels = "%d-%b-%y") +
facet_wrap(~Metric, scales="free") +
ggtitle(unique(.$Methodology))
)
pl[[1,2]]我看到的输出是:

但是,我希望看到由stat_summary或某些类似例程计算的IQR显示为带状图,以及显示中间值的线条。
我怀疑我将不得不编写一个用户定义的函数,并尝试使用它。
感谢任何提示或提示。
发布于 2018-01-08 11:51:44
您可以在geom_smooth中使用stat_summary
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参数。
发布于 2019-07-15 17:02:33
R或ggplot 2中的某些内容发生了变化,但stat_summary()不再使用geom =‘平滑’选项。它需要是geom = 'ribbon‘。这与R 3.6.0和ggplot 3.1.1中所宣传的一样
library(ggplot2)
set.seed(47)
ggplot(tibble::data_frame(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') +
stat_summary(fun.data = median_hilow, fun.args = list(conf.int = 0.5),
geom = 'ribbon', color = 'red', fill = 'red', alpha = 0.2)https://stackoverflow.com/questions/48143852
复制相似问题