Using code below, I create 3 samples, set p1, p2 and p3's parameters for df1, df2, df3 respectively:
set.seed(1)
df1 <- slice_sample(iris, n = 10)
df2 <- slice_sample(iris, n = 10)
df3 <- slice_sample(iris, n = 10)
# to set df1's and arguments (seems not good enough to store parameters, maybe I need to save it as config or ymal file?)
df1_plot1_param <- c(df='df1', x='Petal.Width', y='Sepal.Width', col='Species')
df1_plot2_param <- c(df='df1', x='Petal.Length', y='Sepal.Width', fill='Species')
df1_plot3_param <- c(df='df1', x='Sepal.Width', y='Petal.Width', col='Species')
# to set df2's arguments
df2_plot1_param <- c(df='df2', x='Sepal.Length', y='Sepal.Width', col='Species')
df2_plot2_param <- c(df='df2', x='Petal.Length', y='Sepal.Width', fill='Species')
df2_plot3_param <- c(df='df2', x='Sepal.Length', y='Petal.Width', col='Species')
# to set df3's arguments
df3_plot1_param <- c(df='df3', x='Sepal.Length', y='Sepal.Width', col='Species')
df3_plot2_param <- c(df='df3', x='Petal.Length', y='Sepal.Width', fill='Species')
df3_plot3_param <- c(df='df3', x='Sepal.Length', y='Petal.Width', col='Species')
for i in c(df1's params, df2's params, df3's params):
purrr:map(plot_func(df{i}_param))
The final result will be 3 plots for dfs with parameters pre-defined.
But I don't know how to make the whole code work out, thanks for your help at advance, thanks a lot.
Reference links:
Creating multiple ggplots with dplyr
CodePudding user response:
Try something like this. You can specify the X/Y and the grouping etc in the function.
EDIT: added dataframe as argument to function per the question
set.seed(1)
df1 <- slice_sample(iris, n = 10)
library(ggplot2)
library(patchwork)
my_plot = function(DF=df, X="", Y="", GROUP=""){
# Create ggplot2 scatterplot
p1 <- ggplot(DF,
aes(x = .data[[X]],
y = .data[[Y]],
col = Species))
geom_point()
p1
# Create ggplot2 barchart
p2 <- ggplot(DF,
aes(x = .data[[GROUP]],
y = .data[[Y]],
fill = .data[[GROUP]]))
geom_bar(stat = "identity")
p2
# Create ggplot2 boxplot
p3 <- ggplot(DF,
aes(x = .data[[GROUP]],
y = .data[[Y]],
col = .data[[GROUP]]))
geom_boxplot()
p3
# Create plot composition
p <- (p1 p2) / p3
# Draw plot composition
return(p)
}
test = my_plot(DF=iris, X= "Sepal.Length",Y = "Sepal.Width", GROUP="Species")

