temor
temor

Reputation: 1029

How to sort a barplot of a matrix?

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

That works fine but I need to order each group (separately) by decreasing, i.e. show the same plot but order from high to low for W, …, Z. Example: for W, green will be first from left, blue, yellow, …. For x, green will be first from left, orange, yellow, and so on.

Upvotes: 3

Views: 2147

Answers (1)

missuse
missuse

Reputation: 19716

This can be achieved by generating the colors vector which has as many elements as there are bars and sorting each matrix column separately:

sort the colors according to x order for each column and convert to vector:

colours <- as.vector(apply(data, 2, function(x){
  col <- colours[order(x)]
  }))

sort each column separetely:

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

for descending order and with legend

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)

Here one color vector was used to color the bars and another for the legend

enter image description here

and finally for the question in the comments about aggregated data:

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

Upvotes: 3

Related Questions