作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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
,绿色将从左边开始,橙色、黄色等等。
最佳答案
这可以通过生成具有与条形一样多的元素的颜色向量并分别对每个矩阵列进行排序来实现:
根据每列的 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)
这里使用一个颜色向量为条形图着色,另一个颜色向量用于图例
最后是关于聚合数据的评论中的问题:
all <- apply(data, 1, mean)
colours <- c("red", "orange", "blue", "yellow", "green")
barplot(sort(all, decreasing = T), col = colours[order(all, decreasing = T)])
关于r - 如何对矩阵的条形图进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424696/
我是一名优秀的程序员,十分优秀!