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

后端 未结 2 1934
栀梦
栀梦 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")

提交回复
热议问题