How to order bars in faceted ggplot2 bar chart

后端 未结 2 636
自闭症患者
自闭症患者 2020-12-05 20:53

If I want to order the bars in a ggplot2 barchart from largest to smallest, then I\'d usually update the factor levels of the bar category, like so

one_group         


        
相关标签:
2条回答
  • 2020-12-05 21:32

    Here is a hack to achieve what you want. I was unable to figure out how to get the category values below the tick marks. So if someone can help fix that, it would be wonderful. Let me know if this works

    # add a height rank variable to the data frame
    two_groups = ddply(two_groups, .(group), transform, hrank = rank(height));
    
    # plot the graph
    
    p_two_groups <- ggplot(two_groups, aes(-hrank, height)) +
      geom_bar(stat = "identity") +
      facet_grid(. ~ group, scales = "free_x") +
      opts(axis.text.x = theme_blank()) +
      geom_text(aes(y = 0, label = category, vjust = 1.5))
    
    0 讨论(0)
  • 2020-12-05 21:42

    here is a hack:

    two_groups <- transform(two_groups, category2 = factor(paste(group, category)))
    two_groups <- transform(two_groups, category2 = reorder(category2, rank(height)))
    
    ggplot(two_groups, aes(category2, height)) +
      geom_bar(stat = "identity") +
      facet_grid(. ~ group, scales = "free_x") +
      scale_x_discrete(labels=two_groups$category, breaks=two_groups$category2)
    
    1. make UNIQUE factor variable for all entries (category2)
    2. reorder the variable based on the height
    3. plot on the variable: aes(x=category2)
    4. re-label the axis using original value (category) for the variable (category2) in scale_x_discrete.
    0 讨论(0)
提交回复
热议问题