【问题标题】:ggplot2: geom_smooth select observations connections (equivalence to geom_path())ggplot2:geom_smooth 选择观察连接(等效于 geom_path())
【发布时间】:2017-01-21 11:04:29
【问题描述】:

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

那么有没有办法确保平滑曲线按照观察的顺序而不是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

【问题讨论】:

  • 您能否包含您的数据子集(使用dputhead)以便这是more reproducible
  • 我希望我所做的编辑符合您的要求。谢谢!
  • 您可以尝试使用 coord_flip 并交换 x 和 y,但方面往往会带来一些麻烦。否则,您可能必须首先在ggplot 之外进行平滑处理。看看?loess
  • 我确实考虑过loess,但后来我在 geom_smooth 中使用黄土对象时遇到了困难。但是,如果您对黄土有见解,我会很高兴听到的!

标签: r ggplot2 smooth


【解决方案1】:

您提供的数据非常少,但我们可以让它发挥作用。

使用一些 tidyverse 包,我们可以为每个 variables 安装单独的 loess 函数。

本质上,我们所做的是

  1. variable (group_by) 对我们的数据进行分组。
  2. 使用do 为每个组拟合一个黄土函数。
  3. 使用augment 从该黄土模型创建预测,在本例中为数据范围内的 1000 个值(针对该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 调用中使用该预测数据:

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'))

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

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多