首页 文章

如何使用ggplot / geom_bar订购休息时间

提问于
浏览
3

我有一个data.frame,其条目如下:

variable  importance order
1       foo  0.06977263     1
2       bar  0.05532474     2
3       baz  0.03589902     3
4     alpha  0.03552195     4
5      beta  0.03489081     5
       ...

在使用breaks =变量绘制上述内容时,我希望保留顺序,而不是按字母顺序排列 .

我正在渲染:

ggplot (data, aes(x=variable, weight=importance, fill=variable)) + 
    geom_bar() + 
    coord_flip() + opts(legend.position='none')

但是,变量名的顺序是按字母顺序排列的,而不是数据框中的顺序 . 我看过一篇关于在aes中使用“order”的帖子,但似乎没有任何效果 .

我希望有一个与“订单”列一致的休息订单 .

似乎有一个类似的问题How to change the order of discrete x scale in ggplot,但坦率地说,在这种背景下没有理解答案 .

4 回答

  • 6

    尝试:

    data$variable <- factor(data$variable, levels=levels(data$variable)[order(-data$order)])
    

    来自:ggplot2 sorting a plot Part II

  • 4

    更短更容易理解:

    data$Variable <- reorder(data$Variable, data$order)
    
  • 2

    另一种解决方案是绘制订单,然后在事实之后更改标签:

    df <- data.frame(variable=letters[c(3,3,2,5,1)], importance=rnorm(5), order=1:5)
    p <- qplot(x=order, weight=importance, fill=variable, data=df, geom="bar") + 
      scale_x_continuous("", breaks=1:5, labels=df$variable) + 
      coord_flip() + opts(legend.position='none')
    
  • 1

    在黑暗中拍摄,但也许是这样的:

    data$variable <- factor(data$variable, levels=data$variable)
    

相关问题