Reputation: 31
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")
How do I get these to overlay into a single graph?
Upvotes: 2
Views: 278
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()
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'))
Upvotes: 2