Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order the ggplot x-axis using a list

Tags:

r

ggplot2

I have a dataframe I would like to plot as a barchart but I would like the categorical x-values to be in a specific order that I specify with a list. I will show an example using the mtcars dataset.

#get a small version of the mtcars dataset and add a named column
mtcars2 <- mtcars
mtcars2[["car"]] <- rownames(mtcars2)
mtcars2 <- mtcars[0:5,]
# I would like to plot this using the following
p = ggplot(mtcars2, aes(x=car, y=mpg))+ geom_bar(stat="identity")

The values of the x-axis are sorted in alphabetical order. But what if I have a list of cars and i would like ggplot to preserve the order:

#list out of alphabetical order
orderlist = c("Hornet 4 Drive", "Mazda RX4 Wag", "Mazda RX4",
               "Datsun 710", "Hornet Sportabout") 

# I would like to plot the bar graph as above but preserve the plot order
# something like this:
p = ggplot(mtcars2, aes(x= reorder( car, orderlist), y=mpg))+ geom_bar(stat="identity")

Any pointers would be appreciated, zach cp

like image 871
zach Avatar asked Feb 13 '26 06:02

zach


1 Answers

Set the levels on the car factor to the order you want them, e.g.:

mtcars2 <- transform(mtcars2, car = factor(car, levels = orderlist))

Then the plot works without any further intervention:

ggplot(mtcars2, aes(x=car, y=mpg))+ geom_bar(stat="identity")

enter image description here

like image 99
Gavin Simpson Avatar answered Feb 15 '26 19:02

Gavin Simpson