如何在ggplot2或R中绘制雷达图

时间:2015-04-04 23:14:59

标签: r plot ggplot2 radar-chart

我正在尝试制作一个雷达图,如附加image使用和ggplot2(或R中的任何其他包)。This谈论这个,但我的情况不同,因为我试图创建具有特定范围的响应数据的蜘蛛图。 我使用如下代码制作了一个情节,但我无法弄清楚如何在图像中制作它。请帮助我。

Impcts <- c("system","supply","security","well-being")
present <- c(5,5,3,5)
past <- c(6,6,4,5)
group.names <- c("present", "past")
ddf.pre <- data.frame(matrix(c(rep(group.names[1], 4), Impcts), nrow = 4,      ncol = 2), var.order = seq(1:4), value = present)
ddf.pas <- data.frame(matrix(c(rep(group.names[2], 4), Impcts), nrow = 4, ncol = 2), var.order = seq(1:4), value = past)
 ddf <- rbind(ddf.pre, ddf.pas)
 colnames(ddf) <- c("Group", "Impcts", "var.order", "var.value")
 library(ggplot2)
 ggplot(ddf, aes(y = var.value, x = reorder(Impcts, var.order),
 group =   Group, colour = Group))+
 coord_polar() + 
 geom_path() +
 geom_point()+
 labs(title = "Impacts Analysis").

enter image description here

1 个答案:

答案 0 :(得分:4)

这是我的尝试。首先,我使用geom_path()绘制了正方形。然后,我使用geom_polygon()在方块顶部绘制了两个多边形。最后我添加了注释。

### Draw squares
mydf <- data.frame(id = rep(1:6, each = 5),
                   x = c(0, 6, 0, -6, 0,
                         0, 5, 0, -5, 0,
                         0, 4, 0, -4, 0,
                         0, 3, 0, -3, 0,
                         0, 2, 0, -2, 0,
                         0, 1, 0, -1, 0),
                   y = c(6, 0, -6, 0, 6,
                         5, 0, -5, 0, 5,
                         4, 0, -4, 0, 4,
                         3, 0, -3, 0, 3,
                         2, 0, -2, 0, 2,
                         1, 0, -1, 0, 1))

g <- ggplot(data = mydf, aes(x = x, y = y, group = factor(id)) +
     geom_path()

### Draw polygons
mydf2 <- data.frame(id = rep(7:8, each = 5),
                    x = c(0, 6, 0, -5, 0,
                          0, 5, 0, -5, 0),
                    y = c(6, 0, -4, 0, 6,
                          5, 0, -3, 0, 5))

gg <- g +
      geom_polygon(data = mydf2, aes(x = x, y = y, group = factor(id), fill = factor(id))) +
      scale_fill_manual(name = "Time", values = c("darkolivegreen4", "brown4"),
                        labels = c("Past", "Present"))


### Add annotation

mydf3 <- data.frame(x = c(0, 6.5, 0, -6.5),
                    y = c(6.5, 0, -6.5, 0),
                    label = c("system", "supply", "security", "well-being"))


ggg <- gg + 
       annotate("text", x = mydf3$x, y = mydf3$y, label = mydf3$label, size = 3)

ggsave(ggg, file = "name.png", width = 10, height = 9)

enter image description here