如何对矩阵的条形图进行排序?

时间:2018-01-24 14:21:00

标签: r sorting plot

data <- structure(list(W= c(1L, 3L, 6L, 4L, 9L), X = c(2L, 5L, 
4L, 5L, 12L), Y = c(4L, 4L, 6L, 6L, 16L), Z = c(3L, 5L, 
6L, 7L, 6L)), .Names = c("W", "X", "Y", "Z"),
     class = "data.frame", row.names = c(NA, -5L))
colours <- c("red", "orange", "blue", "yellow", "green")

barplot(as.matrix(data), main="My Barchart", ylab = "Numbers", 
          cex.lab = 1.5, cex.main = 1.4, beside=TRUE, col=colours).

barchars

工作正常,但我需要通过减少来对每个组(单独)进行排序,即显示相同的情节,但W,...,Z从高到低排序。示例:对于W,绿色将首先从左侧,蓝色,黄色,....对于x,绿色将首先从左侧,橙色,黄色等等。

1 个答案:

答案 0 :(得分:3)

这可以通过生成颜色向量来实现,该颜色向量包含与条形图一样多的元素并分别对每个矩阵列进行排序:

根据每列的x顺序对颜色进行排序并转换为vector:

colours <- as.vector(apply(data, 2, function(x){
  col <- colours[order(x)]
  }))

对每一列进行分类:

df <- apply(data, 2, sort)

barplot(df,
        main = "My Barchart",
        ylab = "Numbers",
        cex.lab = 1.5,
        cex.main = 1.4,
        beside = TRUE,
        col = colours)

enter image description here

降序和图例

colours <- c("red", "orange", "blue", "yellow", "green")

colours1 <- as.vector(apply(data, 2, function(x){
  col <- colours[order(x, decreasing = TRUE)]
  }))

barplot(apply(data, 2, sort,  decreasing = TRUE),
        main = "My Barchart",
        ylab = "Numbers",
        cex.lab = 1.5,
        cex.main = 1.4,
        beside = TRUE,
        col = colours1)

legend("topleft", c("First","Second","Third","Fourth","Fifth"), cex=1.3, bty="n", fill=colours)

这里使用一个颜色矢量为条形图着色,另一个颜色矢量用于图例

enter image description here

最后是关于汇总数据的评论中的问题:

all <- apply(data, 1, mean)
colours <- c("red", "orange", "blue", "yellow", "green")

barplot(sort(all, decreasing = T), col = colours[order(all, decreasing = T)])

enter image description here