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

标签 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,绿色将从左边开始,橙色、黄色等等。

最佳答案

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

根据每列的 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)

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

关于r - 如何对矩阵的条形图进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424696/

相关文章:

R plot - 在一个点上画一个大圆圈

java - 如何按降序对包含字符串的 arrayList 进行排序

python - 修改 Pandas 每小时时间轴上的刻度数

R 密码保护 .rdata 数据文件

r - ggplot2 的 geom_line 中线条的大小不同

ios - 按关系属性对 NSFetchedResultsController 排序? NSFetchRequest NSSortDescriptor

Java:查找具有最高值的字符串

R:layout() 影响绘图区域的边距大小

r - 如何动态创建具有整洁评估的列?

r - 用一种优雅的方法来计算矩阵的每一列中元素的数量大于其他每一列中的元素的数量?