11thal11thal
11thal11thal

Reputation: 333

How to overlay density ggplots from different datasets in R?

I have three ggplots (g1, g2, g3).

They are all from different datasets, and they each have the same xlim and ylim.

I would like to plot them all on one page and overlay them.

I have only found resources online explaining how to plot multiple density plots from the same dataset on the same page.

Is there code I can write so that all subsequent plots are plotted on the same page?

Upvotes: 1

Views: 4985

Answers (1)

stefan
stefan

Reputation: 123783

As @Phil pointed out you can't overlay different plots. However, you can make one plot containing all three density plots. (; Using mtcars and mpg as example datasets try this:

library(ggplot2)

ggplot() +
  geom_density(aes(mpg, fill = "data1"), alpha = .2, data = mtcars) +
  geom_density(aes(hwy, fill = "data2"), alpha = .2, data = mpg) +
  scale_fill_manual(name = "dataset", values = c(data1 = "red", data2 = "green"))

Upvotes: 7

Related Questions