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)])