3

棒グラフとしてプロットしたいデータフレームがありますが、カテゴリ x 値をリストで指定した特定の順序にしたいと考えています。mtcars データセットを使用した例を示します。

#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

4

1 に答える 1