recharts4r

How to programmatically add radar charts?


Goal

Get data in a shiny app and display a radar chart. The data may have multiple columns with different column names (as user names differ).

Example

Here is a simple example with 3 columns that I put in a radar chart:

library(echarts4r)
library(tibble)

data_long <- tibble::tibble(
  Construct = c("C", "A", "B"),
  radar1 = c(10, 50, 100),
  calcu2 = c(50, 90, 5),
  foker = c(15, 35, 75)
)

data_long |>
  e_charts(Construct) |>
  e_radar(radar1, max = 100) |>
  e_radar(calcu2) |>
  e_radar(foker)

The challenge I have is that the column names other than "Construct" will be user names. So, I would not know the column names beforehand. The e_radar function requires a column name. How do I programmatically build the radar chart without knowing the number and names of columns?


Solution

  • Maybe you can make a generic e_radar function. You can use e_radar_() instead of e_radar()

    library(echarts4r)
    library(tibble)
    
    e_radar_unknown_columns <- function(df = NULL){
      
      radarPlot <- df |>
        e_charts(Construct)
      
      for (i in 2:length(df)){
        radarPlot <- radarPlot |>
          e_radar_(names(df)[i], max = 100)
      }
      
      return(radarPlot)  
    }
    
    data_long <- tibble::tibble(
      Construct = c("C", "A", "B"),
      oter = c(10, 50, 100),
      calcu2 = c(50, 90, 5),
      foker = c(15, 35, 75)
    )
    
    data_long2 <- tibble::tibble(
      Construct = c("C", "A", "B"),
      radar1 = c(10, 50, 100),
      calcu2 = c(1, 100, 55),
      foker = c(50, 40, 90)
    )
    
    data_long3 <- tibble::tibble(
      Construct = letters[1:10],
      name1 = sample(1:100, 10),
      name2 = sample(1:100, 10),
      name3 = sample(1:100, 10),
      name4 = sample(1:100, 10),
      name5 = sample(1:100, 10),
      name6 = sample(1:100, 10),
      name7 = sample(1:100, 10),
      name8 = sample(1:100, 10),
      name9 = sample(1:100, 10)
    )
    
    e_radar_unknown_columns(data_long)
    e_radar_unknown_columns(data_long2)
    e_radar_unknown_columns(data_long3)