DaveR7
DaveR7

Reputation: 31

How to overlay total density and group density using ggdensity

I want to generate a single density plot diagram that shows both the total density and group density plots. For example, using the built in iris data set:

ggdensity(iris, x = "Sepal.Length",add = "mean")+
ggdensity(iris, x = "Sepal.Length", add = "mean", rug = TRUE,
          color = "Species", fill = "Species")

Image produced by two ggdensity calls

How do I get these to overlay into a single graph?

Upvotes: 2

Views: 278

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You can add a geom_density layer for the "grand total" density:

ggdensity(iris, x = "Sepal.Length", add = "mean", rug = TRUE,
          color = "Species", fill = "Species") +
  geom_density()

enter image description here

Note though that the difference in the y axis scale is more apparent. If you want to fix this, you can multiply the grand total density by three and add a second axis:

ggdensity(iris, x = "Sepal.Length", add = "mean", rug = TRUE,
          color = "Species", fill = "Species") +
  geom_density(aes(y = after_stat(density * 3))) +
  scale_y_continuous(sec.axis = sec_axis(~.x/3, name = 'Total density'))

enter image description here

Upvotes: 2

Related Questions