我正在研究一个带有预测和观测的箱线图,这是一个非常长的数据集。我在这里提供样本格式。
> forecasts <- data.frame(f_type = c(rep("A", 9), rep("B", 9)),
Date = c(rep(as.Date("2007-01-31"),3), rep(as.Date("2007-02-28"), 3), rep(as.Date("2007-03-31"), 3), rep(as.Date("2007-01-31"), 3), rep(as.Date("2007-02-28"), 3), rep(as.Date("2007-03-31"), 3)),
value = c(10, 50, 60, 05, 90, 20, 30, 46, 39, 69, 82, 48, 65, 99, 75, 15 ,49, 27))
>
> observation <- data.frame(Dt = c(as.Date("2007-01-31"), as.Date("2007-02-28"), as.Date("2007-03-31")),
obs = c(30,49,57))
到目前为止,我有:
ggplot() +
geom_boxplot(data = forecasts,
aes(x = as.factor(Date), y = value,
group = interaction(Date, f_type), fill = f_type)) +
geom_line(data = observations,
aes(x = as.factor(Dt), y = obs, group = 1),
size = 2)
这样,默认情况下会设置框和胡须。我想分配这些值,以便我知道胡须的范围。我试图用stat_summary传递一个函数,如:
f <- function(x) {
r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
r
}
o <- function(x) {
subset(x, x < quantile(x,probs = 0.05) | quantile(x,probs = 0.95) < x)
}
ggplot(forecasts, aes(x = as.factor(Date), y = value)) +
stat_summary(fun.data = f, geom = "boxplot", aes(group = interaction(Date, f_type), fill = f_type)) +
stat_summary(fun.y = o, geom = "point")
但是,随之而来的是这些团体搞砸了。这会产生堆积的图。 有人怎么做到这一点?
答案 0 :(得分:5)
通过一些预处理,您可以按日期和f_type汇总值,以生成所需的ymin
,lower
,middle
,upper
和ymax
参数geom_boxplot
(诀窍是设置stat = "identity"
):
forecasts %>% group_by(f_type, Date) %>%
summarise( # You can set your desired values/quantiles here
y_min = quantile(value, 0.05),
low = quantile(value, 0.25),
mid = quantile(value, 0.5),
high = quantile(value, 0.75),
y_max = quantile(value, 0.95)
) %>%
ggplot() +
geom_boxplot(
aes(
ymin = y_min,
lower = low,
middle = mid,
upper = high,
ymax = y_max,
x = as.factor(Date),
fill = f_type
),
stat = "identity"
) +
geom_line(
data = observations,
aes(
x = as.factor(Dt),
y = obs, group = 1
),
size = 2
)