creating "radar chart" (a.k.a. star plot; spider plot) using ggplot2 in R

lokheart picture lokheart · Mar 8, 2012 · Viewed 36.6k times · Source

I want to create a plot like the one below:

enter image description here

I know I can use the radarchart function from fmsb package. I wonder if ggplot2 can do so, using polar coordinate? Thanks.

Answer

Richie Cotton picture Richie Cotton · Mar 8, 2012

First, we load some packages.

library(reshape2)
library(ggplot2)
library(scales)

Here are the data from the radarchart example you linked to.

maxmin <- data.frame(
  total  = c(5, 1),
  phys   = c(15, 3),
  psycho = c(3, 0),
  social = c(5, 1),
  env    = c(5, 1)
)
dat <- data.frame(
  total  = runif(3, 1, 5),
  phys   = rnorm(3, 10, 2),
  psycho = c(0.5, NA, 3),
  social = runif(3, 1, 5),
  env    = c(5, 2.5, 4)
)

We need a little manipulation to make them suitable for ggplot.

Normalise them, add an id column and convert to long format.

normalised_dat <- as.data.frame(mapply(
    function(x, mm)
    {
      (x - mm[2]) / (mm[1] - mm[2])
    },
    dat,
    maxmin
))

normalised_dat$id <- factor(seq_len(nrow(normalised_dat)))
long_dat <- melt(normalised_dat, id.vars = "id")

ggplot also wraps the values so the first and last factors meet up. We add an extra factor level to avoid this. This is no longer true.

levels(long_dat$variable) <- c(levels(long_dat$variable), "")

Here's the plot. It isn't quite the same, but it should get you started.

ggplot(long_dat, aes(x = variable, y = value, colour = id, group = id)) +
  geom_line() +
  coord_polar(theta = "x", direction = -1) +
  scale_y_continuous(labels = percent)

enter image description here Note that when you use coord_polar, the lines are curved. If you want straight lines, then you'll have to try a different technique.