我正在使用 ggplot2
创建海洋的垂直剖面。我的原始数据集创建了“尖峰”以形成平滑的曲线。我希望使用 geom_smooth()
。我还希望这条线根据观察的顺序(而不是根据 x 轴)前进。当我使用 geom_path()
时,它适用于原始图,但不适用于生成的 geom_smooth()
(见下图)。
melteddf = Storfjorden %>% melt(id.vars = "Depth")
ggplot(melteddf, aes(y = Depth, x = value)) +
facet_wrap(~ variable, nrow = 1, scales = "free_x") +
scale_y_reverse() +
geom_smooth(span = 0.5,se = FALSE) +
geom_path()
我的数据子集:
head(Storfjorden)
Depth Salinity Temperature Fluorescence
1 0.72 34.14 3.738 0.01
2 0.92 34.14 3.738 0.02
3 1.10 34.13 3.739 0.03
4 1.80 34.14 3.740 0.06
5 2.80 34.13 3.739 0.02
6 3.43 34.14 3.739 0.05
最佳答案
您提供的数据非常少,但我们可以让它发挥作用。
使用一些 tidyverse 包,我们可以为每个变量
拟合单独的 loess 函数。
本质上,我们所做的是
- 按
变量
(group_by
)对我们的数据进行分组。 - 使用
do
为每个组拟合黄土函数。 - 使用
augment
从该黄土模型创建预测,在本例中为数据范围内的 1000 个值(针对该变量
)。
.
# Load the packages
library(dplyr)
library(broom)
lo <- melteddf %>%
group_by(variable) %>%
do(augment(
loess(value ~ Depth, data = .),
newdata = data.frame(Depth = seq(min(.$Depth), max(.$Depth), l = 1000))
))
现在我们可以在新的 geom_path
调用中使用预测数据:
ggplot(melteddf, aes(y = Depth, x = value)) +
facet_wrap(~ variable, nrow = 1, scales = "free_x") +
scale_y_reverse() +
geom_path(aes(col = 'raw')) +
geom_path(data = lo, aes(x = .fitted, col = 'loess'))
(我将简单的字符向量映射到两条线的颜色以创建图例。)
结果:
关于r - ggplot2: geom_smooth 选择观察连接(等同于 geom_path()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39476914/