Reputation: 31033
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
Upvotes: 3
Views: 5973
Reputation: 174813
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")
Upvotes: 10