How do I combine several ggplot2 plots using patchwork?

42 Views Asked by At

When trying to add two ggplot objects (plots) using + from patchwork, I get the error as shown below. What could be the issue?

require(patchwork)
ex.df <- data.table(
  x1 = rnorm(1000, 20, 50),
  x2 = rnorm(1000, 4, 5)
)

plt1 <- ex.df |> 
  ggplot() +
  geom_density(aes(x = x1))

plt2 <- ex.df |> 
  ggplot() +
  geom_density(aes(x = x2))
plt1 + plt2

enter image description here

This happens even when I use the wrap_plots function

1

There are 1 best solutions below

0
Carl On

With data.frame:

(Also works for me with data.table per second plot.)

library(ggplot2)
require(patchwork)

ex.df <- data.frame(
  x1 = rnorm(1000, 20, 50),
  x2 = rnorm(1000, 4, 5)
)

plt1 <- ex.df |> 
  ggplot() +
  geom_density(aes(x = x1))

plt2 <- ex.df |> 
  ggplot() +
  geom_density(aes(x = x2))

plt1 + plt2

Created on 2024-03-17 with reprex v2.1.0

library(data.table)
library(ggplot2)
require(patchwork)

ex.df <- data.table(
  x1 = rnorm(1000, 20, 50),
  x2 = rnorm(1000, 4, 5)
)

plt1 <- ex.df |> 
  ggplot() +
  geom_density(aes(x = x1))

plt2 <- ex.df |> 
  ggplot() +
  geom_density(aes(x = x2))

plt1 + plt2

Created on 2024-03-17 with reprex v2.1.0