R - 如何制作雷达图矩阵,每个图表中有两个图。

R - How to make a matrix of radar charts with each chart having two plots in it.

我正在尝试创建 5 个雷达图,每个图表中有两个图。 因此,我的数据框中的每两行将组成一个雷达图。

示例数据框:

DF 

name     A   B   C   D   E

name1    1   2   3   4   5
name1    3   2   3   5   4
name2    3   5   4   5   5
name2    2   1   5   1   5
name3    1   3   2   4   1
name3    5   4   1   2   2
name4    1   2   3   4   5
name4    5   4   3   2   1
name5    1   2   3   4   5
name5    5   4   3   2   1

df数据框由两个不同的数据框组成。 c(1,3,5,7,9) 行是一个数据框,c(2,4,6,8,10) 行是另一个数据框。我将它们放在一个数据框中,因为我认为将两个图放入一个雷达图中会更容易实现我的最终目标,但如果有更简单、更有效的方法,请告诉我。

我希望第 1 行和第 2 行是一张图表,第 3 行和第 4 行是一张图表,第 5 行和第 6 行是一张图表,第 7 行和第 8 行是一张图表,第 9 行和第 10 行是成为一张图表。

我现在在做什么:

library(fsmb)
library(plyr)
library(dplyr)

colors_border <- c( rgb(0.2,0.5,0.5,0.9), rgb(0.8,0.2,0.5,0.9))
colors_in <- c( rgb(0.2,0.5,0.5,0.4), rgb(0.8,0.2,0.5,0.4))

par(mar=c(1,1,1,1))
layout(matrix(1:5, ncol = 5, nrow = 1, byrow = T))

laply(c(1,3,5,7,9), function(x){
  radarchart(rbind(rep(5,5), rep(1,5), df[c(1,2,3,4,5,6,7,8,9,10),-1]), 
         axistype=1 , 
         pcol=colors_border, 
         pfcol=colors_in,
         title = df$name[x],
         plwd=3, 
         plty=1,
         cglcol="grey", 
         cglty=1, 
         axislabcol="grey", 
         caxislabels=seq(1,5,1), 
         cglwd=0.8,
         vlcex=0.8)
})

如您所见,每个雷达图中都绘制了每一行。

我的实际数据框有 20 行和七个变量。

如果您需要任何进一步的信息,请告诉我。任何帮助表示赞赏。

您不需要使用 lapply

txt <- "name     A   B   C   D   E
name1    1   2   3   4   5
name1    3   2   3   5   4
name2    3   5   4   5   5
name2    2   1   5   1   5
name3    1   3   2   4   1
name3    5   4   1   2   2
name4    1   2   3   4   5
name4    5   4   3   2   1
name5    1   2   3   4   5
name5    5   4   3   2   1"
df <- read.table(text = txt, header = TRUE)
df$type <- rep(1:2, times = 5)

尝试:

by(df, df$name, function(x) {
  barplot(as.matrix(x[1,2:6,drop = FALSE]), col = x$type[1])
  barplot(as.matrix(x[2,2:6,drop = FALSE]), col = x$type[2], add=TRUE)
})

(条形图在这里没有用,只是一个演示。特别是在您的示例中,您可能会在 by 之前放置一个 par(mfrow=c(1,5))。)

这已经完成一半了。它按 name 分组,但随后将不同 type 的数量硬编码为 2。如果可以保证,那么你很好,但如果你有可变数量的 types,那么你可以更深入一层:

by(df, df$name, function(x) {
  by(x, x$type, function(y) {
    barplot(as.matrix(y[,2:6,drop = FALSE]), col = y$type[1], add = y$type[1] != 1)
  })
})

如果你愿意,你可以用 lapply 这样做,结果相同(虽然我认为有点冗长):

lapply(unique(df$name), function(nm) {
  x <- subset(df, name == nm)
  barplot(as.matrix(x[1,2:6,drop = FALSE]), col = x$type[1])
  barplot(as.matrix(x[2,2:6,drop = FALSE]), col = x$type[2], add=TRUE)
})

(同样,您可以嵌套 lapply 调用 type。)