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

血红的双手。 提交于 2021-02-05 07:16:15

问题


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


回答1:


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)
}


来源:https://stackoverflow.com/questions/35914900/add-title-name-to-list-of-ggplots-from-the-names-of-dataframes-in-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!