【问题标题】:ggplot in r: duplicate faceted geom_density and geom_density_ridges resultsr中的ggplot:重复的多面geom_density和geom_density_ridges结果
【发布时间】:2019-08-26 15:10:43
【问题描述】:

ggplot2::geom_density() 的默认设置与一个小平面和ggridges::geom_density_ridges() 产生略有不同的曲线。如何修改其中一种或另一种平滑技术以产生相同的结果?

library(tidyverse)
library(ggridges)

# standard density with facet by cyl ----
mtcars %>%
  ggplot(aes(x = mpg)) +
  geom_density(fill = "gray") +
  facet_wrap(. ~ factor(cyl, levels = c(8, 6, 4)), ncol = 1) +
  theme_minimal()

# density ridge with y = cyl ----
mtcars %>%
  ggplot(aes(x = mpg, y = factor(cyl))) +
  geom_density_ridges() +
  theme_minimal()
#> Picking joint bandwidth of 1.38

reprex package (v0.2.1) 于 2019 年 4 月 4 日创建

【问题讨论】:

    标签: r ggplot2 ggridges


    【解决方案1】:

    您可以使用与geom_density() 相同的统计数据。

    library(tidyverse)
    library(ggridges)
    
    # standard density with facet by cyl ----
    mtcars %>%
      ggplot(aes(x = mpg)) +
      geom_density(fill = "gray") +
      facet_wrap(. ~ factor(cyl, levels = c(8, 6, 4)), ncol = 1) +
      theme_minimal()
    

    # density ridge with y = cyl ----
    mtcars %>%
      ggplot(aes(x = mpg, y = factor(cyl))) +
      geom_density_ridges(stat = "density", aes(height = stat(density))) +
      theme_minimal()
    

    reprex package (v0.2.1) 于 2019 年 4 月 4 日创建

    或者,您可以将geom_density_ridges() 报告的带宽用于geom_density()(此处为bw = 1.38)。

    library(tidyverse)
    library(ggridges)
    
    # density ridge with y = cyl ----
    mtcars %>%
      ggplot(aes(x = mpg, y = factor(cyl))) +
      geom_density_ridges() +
      theme_minimal()
    #> Picking joint bandwidth of 1.38
    

    # standard density with facet by cyl ----
    mtcars %>%
      ggplot(aes(x = mpg)) +
      geom_density(fill = "gray", bw = 1.38) +
      facet_wrap(. ~ factor(cyl, levels = c(8, 6, 4)), ncol = 1) +
      theme_minimal()
    

    reprex package (v0.2.1) 于 2019 年 4 月 4 日创建

    最后两个图看起来略有不同,因为它们具有不同的 x 轴限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多