Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/9614433/creating-radar-chart-a-k-a-star-plot-spider-plot-using-ggplot2-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...