我正在使用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包,我们可以为每个variables
提供单独的黄土函数。
我们基本上做的是
variable
为每个组拟合黄土功能。group_by
从该黄土模型创建预测,在这种情况下,对于数据范围内的1000个值(对于该do
)。.
augment
现在我们可以在新的variable
调用中使用该预测数据:
# 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