0

I have the following dataframe:

group Class Maths Science
Name1 7 74 78
Name2 7 80 91
Name3 6 69 80

I want to create different radar plots for the variables Maths and Science for each classes using R. eg: For the above dataframe, two radar plots should be created for two classes 7 and 6.

nrange <- 2
class <- c(7,6)
for (i in nrange){
plot <- ggradar::ggradar(df[i,2:3], values.radar = c(0, 50, 100), group.line.width = 1,
               group.point.size = 2, legend.position = "bottom", plot.title=class[i])
}
plot

I using the above code. However, it is only creating the plot for the last row. Please help me with this issue.

Thanks a lot in advance!

1 Answers1

0

You were almost there, but there were two little problems.

  1. The for statement evaluated to for(i in 2) which means it is only using i=2. You can fix this by using for(i in 1:nrange)
  2. You were overwriting plot each time through the loop. If you make plot a list and save each graph as a separate element in the list, then it should work.
mydat <- tibble::tribble(
  ~group,   ~Class, ~Maths, ~Science,
"Name1",    7,  74, 78,
"Name2",    7,  80, 91,
"Name3",    6,  69, 80)

plots <- list()
nrange <- 2
class <- c(7,6)
for (i in 1:3){
  plots[[i]] <- ggradar::ggradar(mydat[i,2:4], values.radar = c(0, 50, 100), 
                           grid.max = 100, group.line.width = 1,
                           group.point.size = 2, legend.position = "bottom", plot.title=mydat$Class[i])
}
plots
#> [[1]]

#> 
#> [[2]]

#> 
#> [[3]]

Created on 2023-02-03 by the reprex package (v2.0.1)


Putting Together with facet_wrap()

library(dplyr)
library(ggplot2)
mydat <- tibble::tribble(
  ~group,   ~Class, ~Maths, ~Science,
  "Name1",    7,  74, 78,
  "Name2",    7,  80, 91,
  "Name3",    6,  69, 80)

mydat <- mydat %>% 
  mutate(gp = paste(group, Class, sep=": ")) %>% 
  select(gp, Maths, Science)

  ggradar::ggradar(mydat, values.radar = c(0, 50, 100), 
                                 grid.max = 100, group.line.width = 1,
                                 group.point.size = 2, legend.position = "bottom") + 
    facet_wrap(~gp)

Created on 2023-02-06 by the reprex package (v2.0.1)

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25