Ordering bar plots with ggplot2 according to their size, i.e. numerical value

后端 未结 2 1932
栀梦
栀梦 2021-01-18 05:55

This question asks about ordering a bar graph according to an unsummarized table. I have a slightly different situation. Here\'s part of my original data:

ex         


        
相关标签:
2条回答
  • 2021-01-18 06:29

    With newer tidyverse functions, this becomes much more straightforward (or at least, easy to read for me):

    library(tidyverse)
    
    d %>%
      mutate_at("pvs_id", as.factor) %>%
      mutate(pvs_id = fct_reorder(pvs_id, mqs)) %>%
      gather(variable, value, c(mqs, imcs)) %>% 
      ggplot(aes(x = pvs_id, y = value)) + 
        geom_col(aes(fill = variable), position = position_dodge())
    

    What it does is:

    • create a factor if not already
    • reorder it according to mqs (you may use desc(mqs) for reverse-sorting)
    • gather into individual rows (same as melt)
    • plot as geom_col (same as geom_bar with stat="identity")

    0 讨论(0)
  • 2021-01-18 06:31

    It's all in making

    pvs_id a factor and supplying the appropriate levels to it:

    dat$pvs_id <- factor(dat$pvs_id, levels = dat[order(-dat$mqs), 2])
    
    m = melt(dat, id.var="pvs_id", measure.var=c("mqs","imcs"))
    
    ggplot(m, aes(x=pvs_id, y=value))+ 
        geom_bar(aes(fill=variable), position="dodge", stat="identity")
    

    This produces the following plot:

    EDIT: Well since pvs_id was numeric it is treated in an ordered fashion. Where as if you have a factor no order is assumed. So even though you have numeric labels pvs_id is actually a factor (nominal). And as far as dat[order(-dat$mqs), 2] is concerned the order function with a negative sign orders the data frame from largest to smallest along the variable mqs. But you're interested in that order for the pvs_id variable so you index that column which is the second column. If you tear that apart you'll see it gives you:

    > dat[order(-dat$mqs), 2]
    [1] 6 2 0 5 7 4 8 3 1
    

    Now you supply that to the levels argument of factor and this orders the factor as you want it.

    0 讨论(0)
提交回复
热议问题