我有一个相当大的数据框(近 100,000 个观测值,大约有 40 个变量),我希望 ggplot 从中绘制带有 lm 或 loess 线的散点图。但是这些线只能根据每个观察日期的变量值的某个分位数来计算。而且我想直接在 ggplot 中进行过滤或子集化,而无需事先创建新的数据对象或子数据框。
由于我的“真实”数据框太大,我创建了一个虚构的示例,其中包含一个名为df_Bandvals的 144 个观察数据框(文章末尾的代码)。
以下结构,前 25 条线和散点图与基于所有观察的黄土线
> str(df_Bandvals)
'data.frame': 144 obs. of 5 variables:
$ obsdate : int 190101 190101 190101 190101 190101 190101 190101 190101 190101 190101 ...
$ transsect : chr "A" "A" "A" "A" ...
$ PointNr : num 1 2 3 4 5 6 1 2 3 4 ...
$ depth : num 31 31 31 31 31 31 31 31 31 31 ...
$ Band12plusmin: num 169 241 229 159 221 196 188 216 233 149 ...
> df_Bandvals
obsdate transsect PointNr depth Band12plusmin
1 190101 A 1 31 169
2 190101 A 2 31 241
3 190101 A 3 31 229
4 190101 A 4 31 159
5 190101 A 5 31 221
6 190101 A 6 31 196
7 190101 B 1 31 188
8 190101 B 2 31 216
9 190101 B 3 31 233
10 190101 B 4 31 149
11 190101 B 5 31 169
12 190101 B 6 31 181
13 190102 A 1 3 356
14 190102 A 2 3 368
15 190102 A 3 3 293
16 190102 A 4 3 261
17 190102 A 5 3 313
18 190102 A 6 3 374
19 190102 B 1 3 327
20 190102 B 2 3 409
21 190102 B 3 3 369
22 190102 B 4 3 334
23 190102 B 5 3 376
24 190102 B 6 3 318
25 190103 A 1 25 183
该图显示了深度与Band12plusmin 的关系,并带有相应的黄土线。点颜色分配给相应的观察日期 ( obsdate )。每个观测日期包括 12 个观测。
现在,我的基本问题是:如何仅根据每个观测日期的较低 50% 分位数Band12plusmin值来获得黄土线?或者换句话说,参考绘图:ggplot 应该只使用每种颜色的 6 个较低的点来计算线。
如前所述,我想直接在 ggplot 中进行过滤或子集化,而无需提前创建新的数据对象或子数据框。
我尝试了子集化,但在这种情况下我的问题是我不能只指定一个通用的Band12plusmin -threshold 因为,当然,每个obsdate -group的 50%-treshold 单独不同。我对 R 和 ggplot 很陌生,所以,现在我没能找到一个解决方案,比如类-个体-派生-阈值条件过滤。有人可以在这里帮忙吗?
这里是数据框和绘图的代码
obsdate<-rep(c(190101:190112),each=12, mode=factor)
transsect<-rep(rep(c("A","B"), each=6), 12)
PointNr<-rep(c(1,2,3,4,5,6), times=24)
depth<-rep(c(31,3,25,-9,13,18,7,-10,3,-4,11,21),each=12)
Band12<-rep(c(199,349,225,844,257,231,301,875,378,521,210,246), each=12)
set.seed(13423)
plusminRandom<-round(rnorm(144, mean=0, sd=33))
plusminRandom
Band12plusmin<-Band12+plusminRandom
df_Bandvals<-data.frame(obsdate, transsect, PointNr, depth, Band12plusmin)
str(df_Bandvals)
head(df_Bandvals, 20)
library (ggplot2)
ggplot(data=df_Bandvals, aes(x=depth, y=Band12plusmin))+
scale_x_continuous(limits = c(-15, 35))+
scale_y_continuous(limits = c(120, 960))+
geom_point(aes(color=factor(obsdate)), size=1.5)+
geom_smooth(method="loess")
您应该能够在其中使用data
参数geom_smooth()
ggplot(data = df_Bandvals, aes(x = depth, y = Band12plusmin)) +
scale_x_continuous(limits = c(-15, 35)) +
scale_y_continuous(limits = c(120, 960)) +
geom_point(aes(color = factor(obsdate)), size = 1.5) +
geom_smooth(
data = df_Bandvals %>%
group_by(obsdate) %>%
filter(Band12plusmin < median(Band12plusmin)),
method = "loess"
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句