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

任何指针将不胜感激,
扎克

最佳答案

car 因子上的级别设置为您想要的顺序,例如:

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

然后情节在没有任何进一步干预的情况下工作:
ggplot(mtcars2, aes(x=car, y=mpg))+ geom_bar(stat="identity")

关于r - 使用列表对 ggplot x 轴进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16547998/

10-12 14:01