Home > Enterprise >  How to combine two ggplot2 objects into one plot (not figure)?
How to combine two ggplot2 objects into one plot (not figure)?

Time:06-19

I've created two ggplot2 objects with histogram layers and stored them for later use. I'd like to merge them so that histogram from plt1 is now semi-transparent and overlaid on top of plt2, both in one plot. How can I:

  1. add alpha to a histogram after it is created?
  2. merge the plots together?

They are based on different data. Note: I know how to plot two datasets in one plot. I want to merge plots that are already created, somehow restore data from them). MRE:

library(tidyverse)

data1 = data.frame(x = rnorm(300, 0, 1))
data2 = data.frame(x = rnorm(300, 1, 3))
plt1 = ggplot(data1, aes(x = x, y = ..density..))   geom_histogram()
plt2 = ggplot(data2, aes(x = x, y = ..density..))   geom_histogram()

CodePudding user response:

Link to a similar question that may help

df1 <- data.frame(x = seq(2, 8, by = 2),
              y = seq(30, 15, by = -5))
[df2 <- data.frame(x = seq(2, 8, by = 2),
                  y = seq(12, 24, by = 4))][1]

ggplot(df1, aes(x, log(y)))   
   geom_line()  
   geom_line(data = df2, color = "red") # re-define data and overwrite top layer inheritance

Overlaying two plots using ggplot2 in R

Also here is the answer to your question on setting alpha

#example of using alpha to fade scatter point markers    
p   geom_point(alpha = 1/10)

ggplot2

CodePudding user response:

You could use bind_rows to bind and name (using .id) the two datasets, then plot them together with some alpha:

library(tidyverse)

set.seed(123)

data1 = data.frame(x = rnorm(300, 0, 1))
data2 = data.frame(x = rnorm(300, 1, 3))

both_df <- bind_rows(data1 = data1, data2 = data2, .id = "dataset")

ggplot(both_df, aes(x, ..density.., fill = dataset))   
  geom_histogram(alpha = 0.6, position = "identity")

Created on 2022-06-18 by the reprex package (v2.0.1)

  • Related