r - order the ggplot x-axis using a list -


i have dataframe plot barchart categorical x-values in specific order specify list. show example using mtcars dataset.

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

the values of x-axis sorted in alphabetical order. if have list of cars , ggplot preserve order:

#list out of alphabetical order orderlist = c("hornet 4 drive", "mazda rx4 wag", "mazda rx4",                "datsun 710", "hornet sportabout")   # plot bar graph above preserve plot order # this: p = ggplot(mtcars2, aes(x= reorder( car, orderlist), y=mpg))+ geom_bar(stat="identity") 

any pointers appreciated, zach cp

set levels on car factor order want them, e.g.:

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

then plot works without further intervention:

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

enter image description here


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -