同一图中的多个分布-使用ggplot2中的geom_density函数

时间:2018-10-17 00:35:22

标签: r ggplot2 tidyverse

我想我已经很接近完成此代码了,但是我在这里遗漏了一些东西。 我想像这样将两个图“组合”成一个图:

Normal distributions 第一个情节具有以下代码:

  ggplot(test, aes(y=key,x=value)) + 
  geom_path()+
  coord_flip()

第二个在下面:

  ggplot(test, aes(x=value, fill=key)) +
  geom_density() +
  coord_flip()

当我们读到正态分布时,这种多分布图通常会在统计书中看到。到目前为止,我最有用的链接是此here

请使用以下代码重现我的问题:

library(tidyverse)
test <- data.frame(key = c("communication","gross_motor","fine_motor"),
                   value = rnorm(n=30,mean=0, sd=1))
ggplot(test, aes(x=value, fill=key)) +
  geom_density() +
  coord_flip()

ggplot(test, aes(y=key,x=value)) + 
  geom_path(size=2)+
  coord_flip()

非常感谢

2 个答案:

答案 0 :(得分:5)

您可能对ggridges软件包中的山脊线图感兴趣。

  

Ridgeline图是部分重叠的线图,可产生山脉的印象。对于可视化时间或空间分布的变化,它们非常有用。

library(tidyverse)
library(ggridges)

set.seed(123)
test <- data.frame(
  key = c("communication", "gross_motor", "fine_motor"),
  value = rnorm(n = 30, mean = 0, sd = 1)
)

ggplot(test, aes(x = value, y = key)) + 
  geom_density_ridges(scale = 0.9) + 
  theme_ridges() +
  NULL
#> Picking joint bandwidth of 0.525

添加中线:

ggplot(test, aes(x = value, y = key)) +
  stat_density_ridges(quantile_lines = TRUE, quantiles = 2, scale = 0.9) +
  coord_flip() +
  theme_ridges() +
  NULL
#> Picking joint bandwidth of 0.525

模拟地毯:

ggplot(test, aes(x = value, y = key)) + 
  geom_density_ridges(
    jittered_points = TRUE,
    position = position_points_jitter(width = 0.05, height = 0),
    point_shape = '|', point_size = 3, point_alpha = 1, alpha = 0.7,
  ) +
  theme_ridges() +
  NULL
#> Picking joint bandwidth of 0.525

reprex package(v0.2.1.9000)于2018-10-16创建

答案 1 :(得分:2)

我认为最简单的方法是使用facet_wrap()。如果您不喜欢这些方面的默认外观,则可以使用theme()对其进行调整,例如:

ggplot(test, aes(x=value, fill=key)) +
    geom_density() +
    facet_wrap(~ key) +
    coord_flip() +
    theme(panel.spacing.x = unit(0, "mm"))

结果:

density plots