Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-ordering bars in R's barplot()

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?

like image 607
Juddy Avatar asked May 27 '16 10:05

Juddy


People also ask

How do I change the order of bars in a barplot in R?

To reorder bars manually, you have to pass stat=”identity” in the geom_bar() function. Example: R.

How do you sort a bar chart in descending order in R?

Rearranging Results in Basic R Then draw the bar graph of the new object. If you want the bar graph to go in descending order, put a negative sign on the target vector and rename the object. Then draw the bar graph of the new object.

How do I change the width of a barplot bar in R?

To Increase or Decrease width of Bars of BarPlot, we simply assign one more width parameter to geom_bar() function. We can give values from 0.00 to 1.00 as per our requirements.


1 Answers

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

like image 53
ArunK Avatar answered Oct 07 '22 13:10

ArunK