MRF
MRF

Reputation: 377

Add title name to list of ggplots from the names of dataframes in list

I am producing a list of boxplots from a list of data frames as so:

Bps<-lapply(dflist, function(x){
  gg<-ggplot(x, aes(x= x, y= y, fill= x))+
   geom_boxplot(position  = "dodge")+
    ggtitle(names(x))    
 })

The list of dataframes can be generated by:

 df1<-data.frame(x=seq(1:50), y=rep("Blank", "Non_blank",25))
 df2<-data.frame(x=seq(1:40), y=rep("Blank", "Non_blank",20))
 df3<-data.frame(x=seq(1:30), y=rep("Blank", "Non_blank",15))

dflist<-list(df1,df2,df3

I need to paste the names of the original dataframes as the title for each boxplot. So if dflist has 3 dataframes called dfA, dfB and dfC, these should be the titles of each boxplot made from the lapply function. I can only seem to get the name of a column and not the original dataframe name. Many thanks, M

Upvotes: 3

Views: 2339

Answers (1)

mtoto
mtoto

Reputation: 24198

Since this is a sequential problem and we don't need to assign the outcome, we can use a for loop:

names(dflist) <- c("dfA", "dfB", "dfC") # Define names of df's

for (i in seq(dflist)) {
  gg <- ggplot(dflist[[i]], aes(x = x, y = y, fill = x))+
    geom_boxplot(position  = "dodge") +
    ggtitle(names(dflist[i]))
  print(gg)
}

Upvotes: 6

Related Questions