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

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

问题描述

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



我知道我可以使用

/ func.php?rd_id=fmsb:radarchartrel =noreferrer> radarchart 功能来自 fmsb 包。我想知道 ggplot2 可以使用极坐标吗?感谢。

解决方案

首先,我们加载一些包。

<$ p $
library(scale)
library(reshape2)
library(ggplot2)

以下是您链接到的radarchart示例的数据。

  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),$ b $ (3,10,2),
psycho = c(0.5,NA,3),
social = runif(3,1,5),
env = c 5,2.5,4)

我们需要一些操作使它们适用于ggplot。



对它们进行标准化,添加一个id列并将其转换为长格式。

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

水平(long_dat $变量)< - c (long_dat $ variable),)



这是图。它不完全相同,但它应该让你开始。

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


请注意,当您使用 coord_polar 时,线条会弯曲。如果你想要直线,那么你必须尝试不同的技术。


I want to create a plot like the one below:

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

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)

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天全站免登陆