I have a list of data frames that are all of the same structure, and I want to plot information from all of these data frames on the same diagram in R using ggplot, like when facet_wrap is used to show multiple panels on a single image, but am having trouble. below I have created a reproducible example.
library(ggplot)
#Designating 3 datasets:
data_1 <- mtcars
data_2 <- mtcars
data_3 <- mtcars
#Making them into a list:
mylist <- list(data_1, data_2, data_3)
#What things should look like, with facet_wrap being by "dataset", and thus a panel for each of the
#three datasets presented.
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) geom_point() facet_wrap(~Species)
But instead, when I run the following, I get an error saying that the data must be presented as a dataframe, not a list:
ggplot(mylist, aes(x = cyl, y = mpg)) geom_point() facet_wrap(~.x)
Does anyone know the best way to use ggplot to plot from a list like this? Do you have to somehow wrap ggplot within lapply()?
CodePudding user response:
One option would be to bind your dataframes by row using e.g. dplyr::bind_rows
:
library(ggplot2)
data_1 <- mtcars
data_2 <- mtcars
data_3 <- mtcars
mylist <- list(data_1, data_2, data_3) |>
dplyr::bind_rows(.id = "id")
ggplot(mylist, aes(x = cyl, y = mpg)) geom_point() facet_wrap(~id)