创建“雷达图"(又名星图;蜘蛛图)在 R 中使用 ggplot2 [英] creating "radar chart" (a.k.a. star plot; spider plot) using ggplot2 in R

查看:50
本文介绍了创建“雷达图"(又名星图;蜘蛛图)在 R 中使用 ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个如下图所示的图:

I want to create a plot like the one below:

我知道我可以使用 radarchart 函数来自 fmsb 包.我想知道 ggplot2 是否可以这样做,使用极坐标?谢谢.

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

推荐答案

首先,我们加载一些包.

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)
)

我们需要进行一些操作才能使它们适合 ggplot.

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

规范化它们,添加一个 id 列并转换为长格式.

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 还包装了这些值,以便第一个和最后一个因素相遇.我们添加了一个额外的因子水平来避免这种情况. 这不再是正确的.

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)

请注意,当您使用 coord_polar 时,线条是弯曲的.如果您想要直线,则必须尝试不同的技术.

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.

这篇关于创建“雷达图"(又名星图;蜘蛛图)在 R 中使用 ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆