Re-ordering bars in R's barplot()

Juddy picture Juddy · May 27, 2016 · Viewed 61.5k times · Source

What I want to achieve is exactly the same that was already asked here (and specifically using R's base graphics, not packages like ggplot or lattice): Ordering bars in barplot()

However, the solutions proposed there do not seem to work for me. What I need to is the following. Suppose I have this:

num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat <- c(letters[1:length(num)])
data <- data.frame(num, cat)

If I generate a barplot using barplot(data$num), here is what I get:

Now, I want to reorder the bars according to data$cat. Following the link I mentioned above, I tried the accepted answer but got an error:

num2 <- factor(num, labels = as.character(cat))
Error in factor(num, labels = as.character(cat)) : invalid 'labels'; length 10 should be 1 or 9

Then I also tried the other answer there:

num <- as.factor(num)
barplot(table(num))

But here is what I got:

So, in this particular case of mine, which is slightly different from that question, how should I order the barplot so the bars are defined by data$num but ordered according to data$cat?

Answer

ArunK picture ArunK · May 27, 2016

you can use ggplot to do this

library("ggplot2")
num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat <- c(letters[1:10])
data <- data.frame(num, cat)    
ggplot(data,aes(x= reorder(cat,-num),num))+geom_bar(stat ="identity")

The result is as shown below enter image description here

Using base functions

df <- data[order(data$num,decreasing = TRUE),]
 barplot(df$num,names.arg = df$cat)

enter image description here