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

问题描述 投票:3回答:1

我正在使用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
r ggplot2 smooth
1个回答
2
投票

您提供的数据非常少,但我们可以使其工作。

使用一些tidyverse包,我们可以为每个variables提供单独的黄土函数。

我们基本上做的是

  1. 通过qazxsw poi(qazxsw poi)对您的数据进行分组。
  2. 使用variable为每个组拟合黄土功能。
  3. 使用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))
  ))

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

Result:

geom_path

© www.soinside.com 2019 - 2024. All rights reserved.