I have two ggplot objects as below.
library(ggplot2)
set.seed(1)
dat1 = data.frame(x = rnorm(1000), y = rnorm(1000))
dat2 = data.frame(x = rt(5000, 2))
Plot1 = ggplot(data = dat1, aes(x = x, y = y)) + geom_point()
Plot2 = ggplot(dat2) + geom_histogram(aes(x = x))
Now I would like to superimpose Plot2 on Plot1 in the left-middle part of Plot1. Desired output

For better visibility, I also wish to have some transparency with Plot2 so that the Plot1 should not be masked completely in the overlapping region.
Is there any way to achieve that? I have searched over internet for relevant information however all of them seem to be referring to add layers. My final plot will be different from just adding layers.
As partially suggested in a since-deleted answer, we can use patchwork::inset_element() for this.
library(patchwork)
Plot2 = ggplot(dat2) + geom_histogram(aes(x = x)) +
theme_bw() +
theme(
plot.background = element_rect(fill = "#ffffffaa"),
panel.background = element_rect(fill = "#ffffffaa"),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank()
)
Plot1 + inset_element(Plot2, 0, 0.2, 0.3, 0.7)

I used fill="#ffffffaa", though "transparent" gives full transparency.
Edit after extra requirements You may use cowplot::ggdraw to superimpose the plot2-grob over plot1 positioning it within plot 1 using normalized device coordinates [0,1] + setting the background to semi-transparent using panel.background = element_rect(fill = alpha('#D3D3D3', 0.6)
panel.grid = element_blank())library(ggplot2)
library(cowplot)
set.seed(1)
dat1 = data.frame(x = rnorm(1000), y = rnorm(1000))
dat2 = data.frame(x = rt(5000, 2))
Plot1 = ggplot(data = dat1, aes(x = x, y = y)) + geom_point() +
theme(plot.background = element_rect(fill='transparent', color="black"))
Plot2 = ggplot(dat2) + geom_histogram(aes(x = x)) +
theme(
# add half-transparent background
panel.background = element_rect(fill = alpha('#D3D3D3', 0.5)),
# add border color and linewidth if needed
plot.background = element_rect(fill='transparent', color="black", linewidth=1)
)
ggdraw() +
draw_plot(Plot1) +
draw_plot(Plot2, x = 0.05, y = 0.3, width = 0.4, height = 0.4)
# Adjust x,y,width,height as relatives of plot 1 dimensions
# here i set the width of Plot 2 to be 40 % of Plot 1's width
giving

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With