Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting differently with some dataframes r

Tags:

r

ggplot2

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)
like image 236
user13589693 Avatar asked Aug 08 '26 19:08

user13589693


1 Answers

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)

enter image description here

like image 101
StupidWolf Avatar answered Aug 10 '26 10:08

StupidWolf