Question Details

No question body available.

Tags

r ggplot2

Answers (2)

Accepted Answer Available
Accepted Answer
April 29, 2025 Score: 2 Rep: 11,785 Quality: High Completeness: 100%

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 = elementrect(fill = alpha('#D3D3D3', 0.6)

  • plot margins can be defined within the theme of plot2 using this
  • if you want to set more plot elements to transparent, check this out (e.g. hiding the grids panel.grid = elementblank())

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)) + geompoint() + theme(plot.background = elementrect(fill='transparent', color="black"))

Plot2 = ggplot(dat2) + geomhistogram(aes(x = x)) + theme( # add half-transparent background panel.background = elementrect(fill = alpha('#D3D3D3', 0.5)), # add border color and linewidth if needed plot.background = elementrect(fill='transparent', color="black", linewidth=1) )

ggdraw() + drawplot(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

out

April 29, 2025 Score: 3 Rep: 167,786 Quality: Medium Completeness: 70%

As partially suggested in a since-deleted answer, we can use patchwork::insetelement() for this.

library(patchwork)
Plot2 = ggplot(dat2) + geomhistogram(aes(x = x)) +
  themebw() +
  theme(
    plot.background = elementrect(fill = "#ffffffaa"),
    panel.background = elementrect(fill = "#ffffffaa"),
    axis.title = elementblank(),
    axis.text = elementblank(),
    axis.ticks = elementblank()
)
Plot1 + insetelement(Plot2, 0, 0.2, 0.3, 0.7)

two plots, one overlaid as an inset of the other

I used fill="#ffffffaa", though "transparent" gives full transparency.