geom_density creates flat line with facet_wrap

Viewed 38

I try to plot density lines with boxplots, but I just get a flat line that does not resemble the data distribution. What did I miss?

library(tidyverse)
as_tibble(iris) %>%
  pivot_longer(!Species, names_to = "Measure", values_to = "Value") %>%
  ggplot(aes(Value, Measure)) +
  geom_density() +
  geom_boxplot(width = .25, position = position_nudge(y = -.15), outlier.shape = NA) +
  facet_wrap(~ Species, strip.position = "right", nrow = 3)

Created on 2022-08-24 with reprex v2.0.2

1 Answers

You could use geom_density_ridges from ggridges, which calculates the density from the provided data en then plots it like this:

library(tidyverse)
library(ggridges)
as_tibble(iris) %>%
  pivot_longer(!Species, names_to = "Measure", values_to = "Value") %>%
  ggplot(aes(Value, Measure)) +
  geom_density_ridges() +
  geom_boxplot(width = .25, position = position_nudge(y = -.15), outlier.shape = NA) +
  facet_wrap(~ Species, strip.position = "right", nrow = 3)  
#> Picking joint bandwidth of 0.0883
#> Picking joint bandwidth of 0.152
#> Picking joint bandwidth of 0.166

Created on 2022-08-24 with reprex v2.0.2

geom_density is useful to show a smoothed histogram.

Related