I have created a function where the objective is to create a series of plots in a vectorzation way. The functions partially does what I want which is update update the plot based on the selected variables. However, I am not able to pass the label argument (i.e. label_x and label_y) so that the xlab and ylab are updated consistently.
library(tidyverse)
plot_scatter_with_label <- function(df,
var_x,
var_y,
label_x,
label_y,
geom_smooth = FALSE,
point_shape = 16,
point_color = "#EB3300",
point_size = 1,
point_alpha = 1,
smooth_method = "loess",
smooth_se = FALSE,
smooth_color = "navy") {
df <- data.frame(lapply(df, function(x) as.numeric(as.character(x))))
scatter_plot <- function(x, y) {
p <- ggplot(df, aes_string(x = x, y = y)) +
geom_point(shape = point_shape, color = point_color, size = point_size, alpha = point_alpha) +
ylab(label_y) + xlab(label_x)
p
}
map2(
var_y, label_y,
~ map(var_x, scatter_plot, y = .x)
)
}
Example
plot_scatter_with_label(
df = mtcars,
var_y = c("mpg", "hp"),
label_y = c("Miles per gallon [Mpg]", "Horse power [CV]"),
var_x = c("cyl", "gear"),
label_x = c("Cylinders [n]", "Gear [n]")
)
I was expecting to obtain the following plots:
1) mpg vs cyl
2) mpg vs gear
3) hp vs cyl
4) hp vs gear
It appears that I got these 4 plots but the labels are not updated as expected. It always returns the fist argument of defined in label_x and label_y.
Any help would be highly appreciated.
Best regards,