Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Normal distributions 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

like image 417
Luis Avatar asked Apr 09 '26 20:04

Luis


1 Answers

You might be interested in ridgeline plots from the ggridges package.

Ridgeline plots are partially overlapping line plots that create the impression of a mountain range. 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)

like image 120
Tung Avatar answered Apr 12 '26 07:04

Tung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!