I have a list of dataframes saved as df.list. For some dataframes, I would like to plot geom_line AND geom_point (df.1), but for a select few, I would only want only geom_line (df.2, df.3). Is there an efficient way to do this? I am using mapply() for the plotting and can get what I want using mapply() twice, but would like a solution with a single mapply().
Example given below where I tried subsetting, but still only giving plots with lines only, but am trying to get df.1 plotted with lines and points, while df.2/df.3 plotted with only lines.
I have tried subsetting within geom_point, but it looks like you can only subset within a dataframe and not on a list of dataframes.
I have also tried using ifelse, but only the first element would be used for the conditional statement and I don't want to use a loop AND mapply.
df.1 <- iris[1:50,]
df.2 <- iris[51:100,]
df.3 <- iris[101:150,]
df.list <- list(df.1, df.2, df.3)
df.names <- c("df.1", "df.2", "df.3")
names(df.list) <- df.names; list2env(df.list, .GlobalEnv)
name.y <- c("1", "2", "3")
name.x <- c("df.1")
mapply(function(x, k) {
ggplot(x, aes(Sepal.Width, Petal.Length, colour = Species)) +
labs(y = k) + geom_line() + geom_point(data = subset(x, is.element(names(x), name.x)))
}, SIMPLIFY = FALSE, x = df.list, k = name.y)
Most likely you use the list of data.frames directly, it might work.. hopefully this is what you intend to do:
df.list <- list(df.1, df.2, df.3)
df.names <- c("df.1", "df.2", "df.3")
names(df.list) <- df.names; list2env(df.list, .GlobalEnv)
plt = function(x,k){
g = ggplot(x, aes(Sepal.Width, Petal.Length, colour = Species)) +
labs(y = k) + geom_line()
if(k=="1"){
g = g + geom_point()
}
return(g)
}
library(patchwork)
P = mapply(plt, SIMPLIFY = FALSE, x = df.list, name.y)
wrap_plots(P)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With