rspider-chart

square radar chart in R


I'd like to plot a square radar chart (not a rhombus) in R. I tried to use the fmsb library, but it appears to be unable to rotate the chart.

#create data
data_t <- as.data.frame(matrix( sample( 2:20 , 4 , replace=T) , ncol=4))
colnames(data_t) <- c("math" , "english" , "biology" , "music")
data_t <- rbind(rep(20,4) , rep(0,4) , data_t)

radarchart(data_t)

enter image description here


Solution

  • Sure it's possible. With rotated labels, because otherwise it's a bit ugly. Note I had to size down the original labels using vlcex = 0.00000001

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    library(fmsb)
    install.packages("gridGraphics")
    library(gridGraphics)
    
    #create data
    data_t <- as.data.frame(matrix( sample( 2:20 , 4 , replace=T) , ncol=4))
    colnames(data_t) <- c("math" , "english" , "biology" , "music")
    data_t <- rbind(rep(20,4) , rep(0,4) , data_t)
    
    # Create the radar chart
    radarchart(data_t, vlcex = 0.00000001) # put vlcex = 0 and remove the customized label code to preserve the original labels
    
    # Customizing labels
    labels <- colnames(data_t)
    n_labels <- length(labels)
    angles <- seq(0, 2 * pi, length.out = n_labels + 1)[-1]  # Calculate angles for labels
    
    # Add rotated labels manually
    for (i in seq_along(labels)) {
      text(
        x = 1.2 * sin(angles[i]), # Positioning based on sine for x
        y = 1.2 * cos(angles[i]), # Positioning based on cosine for y
        labels[i],
        srt = 45, # Convert radians to degrees and adjust angle
        adj = 1,
        cex = 0.8
      )
    }
    
    
    grab_grob <- function(){
      grid.echo()
      grid.grab()
    }
    
    g <- grab_grob()
    grid.newpage()
    pushViewport(viewport(angle=-45))
    grid.draw(g)
    

    p