Home > front end >  How to superimpose two ggplots
How to superimpose two ggplots

Time:10-20

I have 2 ggplots generated by below codes

library(dplyr)
library(ggplot2)
library(ggdist)
set.seed(1)

DF1 = rbind(data.frame('Label' = 'A', val = rnorm(200, 5)), data.frame('Label' = 'B', val = rnorm(500, 10)))
DF2 = rbind(data.frame('Label' = 'A', val = rt(200, 2)), data.frame('Label' = 'B', val = rt(700, 3)))

Plot1 = ggplot(DF1, aes(x = Label, y = val, fill = 'red'))    stat_dotsinterval(position = 'dodge')
Plot2 = ggplot(DF2, aes(x = Label, y = val, fill = 'green'))   stat_dotsinterval(position = 'dodge')

Plot1
Plot2

Those are individual plots, however I want to combine them into just one ggplot with appropriate legend.

Is there any way to do this for above case?

Any pointer will be highly appreciated.

CodePudding user response:

Similar to eipi10's comment:

library(dplyr); library(ggplot2)
bind_rows(DF1, DF2, .id = "src") %>% 
  mutate(name = if_else(src == "1", "red", "green")) %>%
  ggplot(aes(x=Label, y=val, colour=name, fill=name))     
  stat_dotsinterval()  
  scale_color_identity(aesthetics = c("fill", "color"), guide = "legend")  
  theme(legend.position = "top")

enter image description here

  • Related