【问题标题】:How to sort a barplot of a matrix?如何对矩阵的条形图进行排序?
【发布时间】:2018-07-03 15:05:57
【问题描述】:
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).

这很好,但我需要通过递减来(分别)对每个组进行排序,即显示相同的图,但对于W、...、Z,从高到低排序。示例:对于 W,绿色将是左起第一个,蓝色,黄色,...。对于x,从左到右依次为绿色、橙色、黄色等。

【问题讨论】:

    标签: r sorting plot


    【解决方案1】:

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

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

    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)
    

    用于降序并带有图例

    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)
    

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

    最后是 cmets 中关于聚合数据的问题:

    all <- apply(data, 1, mean)
    colours <- c("red", "orange", "blue", "yellow", "green")
    
    barplot(sort(all, decreasing = T), col = colours[order(all, decreasing = T)])
    

    【讨论】:

      猜你喜欢
      • 2023-02-02
      • 2017-12-06
      • 2022-08-23
      • 2020-11-04
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      相关资源
      最近更新 更多