0 votes
1 view
in R Programming by (5k points)

I am making a dodged bar chart using ggplot with discrete x scale, the x axis are now arranged in alphabetical order, but I need to rearrange it so that it is ordered by the value of the y-axis (i.e., the tallest bar will be positioned on the left).

I tried order or sort, but result in sort the x-axis, but not the bars respectively.

What have I done wrong?

1 Answer

0 votes
by (23.2k points)

To change the order of the discrete x scale, you need to factor the variable and set the levels of the variable that you are plotting.

For example:

In mtcars dataset:

library(ggplot2)

# Automatic levels

data(mtcars)

ggplot(mtcars, aes(cyl)) + geom_bar() 

Output:

image

To factor and set the levels:

 

mtcars$cyl <- factor(mtcars$cyl, levels = names(sort(table(mtcars$cyl), decreasing=TRUE)))

ggplot(mtcars, aes(cyl)) + geom_bar() 

Output:

image

...