Search code examples
rggplot2radar-chart

Cannot store a radar plot into a R object


I was trying to store a radar plot into an object p1 but every time I got a result of null. I tried other ggplot2 plots and they all worked fine of being put into objects. My ultimate intention is to use the patchwork to put one radar plot and one line plot side by side. Any suggestion?

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

# To use the fmsb package, I have to add 2 lines to the dataframe: the max and min of each topic to show on the plot!
data <-rbind(rep(20,10) , rep(0,10) , data)


# Custom the radarChart !
par(mar=c(0,0,0,0))
p1 <- radarchart( data, 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.6 
)

> p1
NULL

Solution

  • Save a plot in an object

    radarchart is not a ggplot2 function, so uses base plot. You can't write base plot to an object but can

    If you want ggplot

    # Run Once Only
    install.packages("devtools")
    devtools::install_github("ricardo-bion/ggradar")
    
    # Run rest as usual
    library(ggplot2)
    library(ggradar)
    library(dplyr)
    library(scales)
    set.seed(99)
    mydata <-as.data.frame(matrix( sample( 2:20 , 10 , replace=T) , ncol=10))
    colnames(mydata) <- c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )
    
    # To use the fmsb package, I have to add 2 lines to the dataframe: the max and min of each topic to show on the plot!
    mydata <-rbind(rep(20,10) , rep(0,10) , mydata)
    
    
    p1 <- ggradar(
      mydata[3, ], 
      values.radar = c("0", "10", "20"),
      grid.min = 0, grid.mid = 10, grid.max = 20
    )
    
    p1
    

    You would obviously need to play with the formatting

    OR if you want to use base R:

    par(mfrow=c(3,1)) will output each new figure into a 3 x 1 grid... but far less controllable than ggplot