Order discrete x scale by frequency/value

前端 未结 5 1067
悲哀的现实
悲哀的现实 2020-11-21 10:57

I am making a dodged bar chart using ggplot with discrete x scale, the x axis are now arranged in alphabetical order, but I need to rearrange it so that it is ordered by the

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 11:58

    I realize this is old, but maybe this function I created is useful to someone out there:

    order_axis<-function(data, axis, column)
    {
      # for interactivity with ggplot2
      arguments <- as.list(match.call())
      col <- eval(arguments$column, data)
      ax <- eval(arguments$axis, data)
    
      # evaluated factors
      a<-reorder(with(data, ax), 
                 with(data, col))
    
      #new_data
      df<-cbind.data.frame(data)
      # define new var
      within(df, 
             do.call("<-",list(paste0(as.character(arguments$axis),"_o"), a)))
    }
    

    Now, with this function you can interactively plot with ggplot2, like this:

    ggplot(order_axis(df, AXIS_X, COLUMN_Y), 
           aes(x = AXIS_X_o, y = COLUMN_Y)) +
            geom_bar(stat = "identity")
    

    As can be seen, the order_axis function creates another dataframe with a new column named the same but with a _oat the end. This new column has levels in ascending order, so ggplot2 automatically plots in that order.

    This is somewhat limited (only works for character or factor and numeric combinations of columns and in ascending order) but I still find it very useful for plotting on the go.

提交回复
热议问题