Search code examples
rdata-visualizationpolygonpolar-coordinatesradar-chart

How to create/enhance my own radar/polar chart without additional packages in R?


I've been trying to create a combination of radar/polar chart of a given vector of polygon vertices, without packages, but just with base R, which I really struggle with. So far, with some help, I have reached the following point:

a <- a <- abs(rnorm(5, mean = 4, sd = 2))
names(a) <- LETTERS[1:5]
stars(matrix(a,nrow=1),axes=TRUE, scale=FALSE,col.lines="blue",radius=FALSE)
center <- c(x=2.1, y=2.1) #the starchart for some reason chooses this as a center
half <- seq(0, pi, length.out = 51)
angle=45
for (D in a) {
  Xs <- D * cos(half); Ys <- D * sin(half)
  lines(center["x"] + Xs, center["y"] + Ys, col = "gray", xpd = NA, lty="dashed")
  lines(center["x"] + Xs, center["y"] - Ys, col = "gray", xpd = NA, lty="dashed")
}

which gives me something this:enter image description here

What I would need to take further is:

  • center this mixed radar/polar chart at (0,0) and mark the center
  • color the polygon area transparently
  • add radii starting from the outermost circle and reaching the center through the polygon vertices
  • put the vector name labels on the ends of the radii on the outermost circle

So, the final result should look something like this:enter image description here

I have experimented with the polygon(), symbols() functions and par() graphic parametres, but I am really struggling to combine them...My problem is that I don't understand how the stars() function plot coordinates selection relates to my input.


Solution

  • Did not liked the stars functions... so I made a full rondabout with polygon:

    polar_chart <- function(values){
      k <- length(values)
      m <- max(values)
      # initialise plot
      plot(1, type="n", xlab="", ylab="", xlim=1.2*m*c(-1,1), ylim=1.2*m*c(-1,1))
      # radial lines & letters
      sapply(k:1, function(x){
        text(1.1*m*cos(-(x-1)*2*pi/k + 2*pi/3), 1.1*m*sin(-(x-1)*2*pi/k + 2*pi/3),
             LETTERS[x], cex = 0.75)
        lines(c(0, m*cos((x-1)*2*pi/k + 2*pi/3)), c(0, m*sin((x-1)*2*pi/k + 2*pi/3)),
              col = "grey",lty="dashed")
        })
      # circles
      aux <- seq(2*pi + 0.1, 0, -0.1)
      sapply(values, function(x) lines(x*cos(aux), x*sin(aux), col = "grey",lty="dashed"))
      # polygon
      x <- values*cos(-(1:k-1)*2*pi/k + 2*pi/3)
      y <- values*sin(-(1:k-1)*2*pi/k + 2*pi/3)
      polygon(c(x, x[1]),c(y, y[1]), col = "red", border = "blue", density = 50)
    }
    
    values <- abs(rnorm(5, mean = 4, sd = 2))
    polar_chart(values)
    

    And returns a plot like the following:

    enter image description here