使用列表命令ggplot x轴

时间:2013-05-14 16:12:39

标签: r ggplot2

我有一个数据框我想绘制成条形图,但我希望分类的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")

任何指针都会受到赞赏, zach cp

1 个答案:

答案 0 :(得分: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