gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:25:35 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com