简体   繁体   English

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

[英]Several distributions in the same plot — using geom_density function from ggplot2

I think I'm very close to getting this code done, but I'm missing something here. 我认为我已经非常接近完成这些代码,但我在这里遗漏了一些东西。 I want to "combine" two plots into just one like this: 我想把两个情节“组合”成这样一个:

正态分布 The first plot has this code: 第一个图有这个代码:

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

And the second one has this one below: 第二个有下面这个:

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

This kind of multiple distributions plot are often seen in stats book when we read about normal distributions. 当我们读到正态分布时,这种多重分布图通常出现在统计书中。 The most useful link I've got so far was this one here . 到目前为止,我已经得到了最有用的链接是这样一个在这里

Please use this code to reproduce my question: 请使用此代码重现我的问题:

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

Thanks much 非常感谢

You might be interested in ridgeline plots from the ggridges package. 您可能对ggridges包中的ridgeline图感兴趣。

Ridgeline plots are partially overlapping line plots that create the impression of a mountain range. Ridgeline图是部分重叠的线图,创造了山脉的印象。 They can be quite useful for visualizing changes in distributions over time or space. 它们对于可视化随时间或空间的分布变化非常有用。

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

Add median line: 添加中线:

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

Simulate a rug: 模拟地毯:

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

Created on 2018-10-16 by the reprex package (v0.2.1.9000) reprex包创建于2018-10-16(v0.2.1.9000)

I think the easiest way to do this is with facet_wrap() . 我认为最简单的方法是使用facet_wrap() If you don't like the default appearance of the facets you can tweak them with theme() , eg: 如果您不喜欢facet的默认外观,可以使用theme()调整它们,例如:

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

Result: 结果:

密度图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM