R中的ggplot:重复的多面geom_density和geom_density_ridges结果

时间:2019-04-04 18:54:05

标签: r ggplot2 ggridges

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-04-04创建

1 个答案:

答案 0 :(得分: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-04-04创建

或者,您可以使用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-04-04创建

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