Reputation: 267
I couldn't find the answer to this problem, so I'm posting it.
I have a stacked barplot that I use to compare the occurrence of different values in my data
Now, I would like to order it in a decreasing order, starting with the biggest combined value. I tried using the method I use for normal barplots:
barplot(combined[order(combined, decreasing = T)],
horiz = T,
las=1,
xlim = c(0,60),
col = c('lightblue','darkblue'))
but it produces a barplot that is no longer stacked
Is there a way to order it properly? I've seen some solutions with ggplot, but I'd prefer sticking to standard barplots, if it's possible.
Thanks!
Upvotes: 1
Views: 528
Reputation: 1631
I'm using the following example to explain the method
num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat <- c(letters[1:10])
data <- data.frame(num, cat)
Now, to generate barplot in decreasing order
barplot(data[order(data[,1],decreasing=FALSE),][,1],names.arg=data[order(data[,1],decreasing=FALSE),][,2], horiz = TRUE)
Hope this example helps.
Upvotes: 1
Reputation: 694
Your problem is that you're using a matrix inside barplot()
function. When you use order and compute combined[order(combined, decreasing=T)]
the result is a vector. If you want to order your columns with no regard to which color would have precedence you may use this code:
barplot(combined[,order(apply(combined, 2, max))])
What this does is to apply the function max()
on the columns (margin 2, margin 1 would be rows) of your matrix. Then you'll have a matrix ordered by the maximum value of each column.
Upvotes: 2