2013-05-14 63 views
3

我有一個數據框我想繪製爲條形圖,但我希望分類x值按照我用列表指定的特定順序。我將使用mtcars數據集顯示一個示例。使用列表排序ggplot x軸使用列表

#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") 

x軸的值按字母順序排序。但是,如果我有車的名單,我想ggplot到訂單保留:

#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") 

任何指針將不勝感激, 扎克CP

回答

10

坐落在car因素的水平,你的訂單希望他們,例如:

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

然後積工作沒有任何進一步的干預:

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

enter image description here

+0

完美!感謝您的回答 – zach 2013-05-14 16:33:44