gpt4 book ai didi

r - ggplot2,带有自定义分位数和异常值的 geom_boxplot

转载 作者:行者123 更新时间:2023-12-04 10:08:24 25 4
gpt4 key购买 nike

我有一个数据集,其中包含 100 次列车运行模拟的数据,该网络具有 4 列火车、6 个车站和每个车站每列火车的到达晚点。我的数据看起来像这样:

MyData <- data.frame(
Simulation = rep(sort(rep(1:100, 6)), 4),
Train_number = sort(rep(c(100, 102, 104, 106), 100*6)),
Stations = rep(c("ST_1", "ST_2", "ST_3", "ST_4", "ST_5", "ST_6"), 100*4),
Arrival_Lateness = c(rep(0, 60), rexp(40, 1), rep(0, 60), rexp(40, 2), rep(0, 60), rexp(40, 3), rep(0, 60), rexp(40, 5))
)

我现在使用自定义分位数为每个火车和车站创建箱线图(感谢 jlhoward):
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
}

ggplot(MyData, aes(factor(Stations), Arrival_Lateness, fill = factor(Train_number))) +
stat_summary(fun.data = f, geom="boxplot", position="dodge")

很漂亮:
enter image description here

我现在缺少的是异常值。我想在每个箱线图的 tom 上为每个火车/车站组合绘制前 5% 的观察结果。我尝试的是这个(灵感来自 this question):
q <- function(x) {
subset(x, quantile(x, 0.95) < x)
}

ggplot(MyData, aes(factor(Stations), Arrival_Lateness, fill = factor(Train_number))) +
stat_summary(fun.data = f, geom="boxplot", position="dodge") +
stat_summary(fun.y = q, geom="point", position="dodge")

我收到一条消息:“ymax 未定义:使用 y 调整位置”,我的图表如下所示:

enter image description here

这显然不是我想要的。

最佳答案

这个?


ggplot(MyData, aes(factor(Stations), Arrival_Lateness, 
fill = factor(Train_number))) +
stat_summary(fun.data = f, geom="boxplot",
position=position_dodge(1))+
stat_summary(aes(color=factor(Train_number)),fun.y = q, geom="point",
position=position_dodge(1))

恕我直言,这更容易解释。


ggplot(MyData, aes(factor(Train_number), Arrival_Lateness, 
fill = factor(Train_number))) +
stat_summary(fun.data = f, geom="boxplot",
position=position_dodge(1))+
stat_summary(aes(color=factor(Train_number)),fun.y = q, geom="point",
position=position_dodge(1))+
facet_grid(.~Stations, scales="free")+
theme(axis.text.x=element_text(angle=-90,hjust=1,vjust=0.2))+
labs(x="Train Number")

编辑 (对 OP 评论的回应)


ggplot(MyData, aes(factor(Train_number), Arrival_Lateness, 
fill = factor(Train_number))) +
stat_summary(fun.data = f, geom="boxplot",
position=position_dodge(1))+
stat_summary(aes(color=factor(Train_number)),fun.y = q, geom="point",
position=position_dodge(1))+
facet_grid(.~Stations, scales="free")+
theme(axis.text.x=element_blank(), axis.ticks.x=element_blank())+
scale_fill_discrete("Train")+scale_color_discrete("Train")+
labs(x="")

要关闭 x 轴文本和刻度线,我们 theme(...=element_blank()) .要关闭轴标签,请使用 labs(x="") .此外,填充和颜色比例必须具有相同的名称,否则它们会单独显示。

关于r - ggplot2,带有自定义分位数和异常值的 geom_boxplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22024551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com