如何在R中的直方图ggplot2上保持分类x的顺序

时间:2015-08-14 14:30:01

标签: r ggplot2 data.table

我想绘制一个直方图,其中包含x上的分类和y上的分数。 表中的顺序应该保存在图中,但是现在情节得到重新排序,我在SO上发现的几个帖子对我的情况没有帮助。例如我试过这个:Order Bars in ggplot2 bar graph

require(data.table)
require(ggplot2)

table <- structure(list(a = c(1, 2, 3, 4, 5, 6), b = c("grease", "surf", 
"lift", "zen", "ufo", "nothing"), c = c("3976.65457028497", "3700.27298336394", 
"3691.44157683915", "3687.89781035758", "3685.83200999925", "3685.44486138222"
)), .Names = c("a", "b", "c"), row.names = c(NA, -6L), class = c("data.table", 
"data.frame"))

ggplot(data=table) + geom_histogram(aes(x=b,y=c),stat='identity')

因此,我按字母顺序对它们进行排序,而我希望它们按顺序递减。我该怎么做?

1 个答案:

答案 0 :(得分:2)

根据我的理解,这就是你要做的事情(我将你的对象表重命名为table.dt):

ggplot(data=table.dt,aes(x=reorder(b,-as.numeric(c)),y=c)) +
  geom_histogram(stat='identity')