-->

How to overlay density ggplots from different data

2020-05-06 00:32发布

问题:

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?

回答1:

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"))

Created on 2020-03-29 by the reprex package (v0.3.0)