Search code examples
rloopsdataframeradar-chart

Loop through a list of dataframes and name the title for each plot


I am referencing this example code to generate a plot that contains multiple subplots with their own titles but having trouble getting the titles of the subplots properly labeled by loop. For the ease of exposition, I use the 1 by 2 plots environment as an example.

par(mfrow(1, 2))
require(fmsb)

data1=as.data.frame(matrix( sample(2:20, 10, replace=T) , ncol=10))
data2=as.data.frame(matrix( sample(2:20, 10, replace=T) , ncol=10))
colnames(data1)=c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )
colnames(data2)=c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )

df1=rbind(rep(20,10) , rep(0,10) , data1)
df2=rbind(rep(20,10) , rep(0,10) , data2)

my.list <- list(df1, df2)

for (i in my.list[[i]]) {

radarchart(i, axistype=1 , 

    #custom polygon
    pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 , 

    #custom the grid
    cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,20,5), cglwd=0.8,

    #custom labels
    vlcex=0.8 
    )
}

However, this code block didn't return anything as it requires the input to be a dataframe. Also, if I want to put a title argument in radarchart() by assigning each dataframe a unique name (say, student 1, student 2) and using them as titles for each subplot, how can I achieve that in a loop?


Solution

  • Your code had some errors, here is the expected output:

    par(mfrow=c(1, 2)) #debugged
    
    library(fmsb)
    
    data1=as.data.frame(matrix( sample(2:20, 10, replace=T) , ncol=10))
    data2=as.data.frame(matrix( sample(2:20, 10, replace=T) , ncol=10))
    colnames(data1)=c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )
    colnames(data2)=c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )
    
    df1=rbind(rep(20,10) , rep(0,10) , data1)
    df2=rbind(rep(20,10) , rep(0,10) , data2)
    
    my.list <- list("df1" = df1, "df2" = df2) #name the list's elements
    
    for (i in 1:length(my.list)) { #use i as list indexer, not to call the elements
    
      radarchart(my.list[[i]], axistype=1 , #call the list's elements
    
                 #custom polygon
                 pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 , 
    
                 #custom the grid
                 cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,20,5), cglwd=0.8,
    
                 #custom labels
                 vlcex=0.8, 
    
                 #title; calling the list's names
                 title = names(my.list)[i] 
      )
    }
    

    enter image description here