r - ggplot2: geom_smooth 选择观察连接(等同于 geom_path())

标签 r ggplot2 smoothing

我正在使用 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()

enter image description here 那么有没有办法让平滑曲线按照观察的顺序而不是a轴进行呢?

我的数据子集:

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 函数。

本质上,我们所做的是

  1. 变量(group_by)对我们的数据进行分组。
  2. 使用 do 为每个组拟合黄土函数。
  3. 使用 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'))

(我将简单的字符向量映射到两条线的颜色以创建图例。)

结果:

enter image description here

关于r - ggplot2: geom_smooth 选择观察连接(等同于 geom_path()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39476914/

相关文章:

r - 如何在R中一起绘制多个堆叠的直方图?

r - ggplot geom_bar:aes(组= 1)的含义

wolfram-mathematica - 实现双指数平滑,即双指数移动平均线 (DEMA)

r - 几何平滑: what is its meaning (why is it lower than the mean?)

r - 使用 strftime 从 Posixct 对象中提取日期和小时

r - 获取字符向量中每个元素的第三个单词

r - 将 POLYGON 聚合为 MULTIPOLYGON 并保留 data.frame

r - 在 .Rmd 文件中使用 knitr 有条件地评估航向

r - 使用ggplot2仅将一个分割添加到一个构面

algorithm - 如何简化样条曲线?