I need to plot about 30 ggplot2 plots from a few different source dataframes, so I wrote a function to create the plots and a params dataframe to store the plot function parameters. I get this error message when passing parameters from the params dataframe to the function:
data
must be a <data.frame>, or an object coercible by fortify()
, not the string “df1”
Here’s my code, and I appreciate any suggestions:
#load libraries
library(tidyverse)
library(ggthemes)
#set up example dataframe:
df1 <- tibble(
date = seq(ymd('2023-01-01'), ymd('2023-06-30'), by='1 month'),
A = runif(6, 1, 20),
B = runif(6, 1, 20),
C = runif(6, 1, 20)
)
#function to create the plots
gen_plots <- function(df, x, y, title){
df |>
ggplot(
mapping = aes(x = {{x}}, y = {{y}})
) +
geom_line() +
geom_point() +
#theme_economist() +
labs(title = {{title}},
y = "$/MWh",
x = NULL)
}
#test the function--it works:
test_plot <- gen_plots(df1, date, A, "Segment A")
#dataframe with plot parameters (source dataframe, x column, y column, & title):
params <- data.frame(
df = c("df1", "df1", "df1"),
x = c("date", "date", "date"),
y = c("A", "B", "C"),
title = c("Segment A", "Segment B", "Segment C")
)
#desired output is a list containing three plots
#this doesn't work
plots <- pmap(params, gen_plots)