Factor order within faceted dotplot using ggplot2

后端 未结 3 1709
终归单人心
终归单人心 2020-12-08 23:47

I\'m trying to change the plotting order within facets of a faceted dotplot in ggplot2, but I can\'t get it to work. Here\'s my melted dataset:

> London.m         


        
3条回答
  •  鱼传尺愫
    2020-12-09 00:32

    This is obviously quite late, and some of what I'm doing may have not been around 6 years ago, but I came across this question while doing a similar task. I'm always reluctant to set tick labels with a vector—it feels safer to use a function that can operate on the original labels.

    To do that, I'm creating a factor ID column based on the country and the medal, with some delimiter character that doesn't already appear in either of those columns—in this case, _ works. Then with forcats::fct_reorder, I can order that column by count. The last few levels of this column are below, and should correspond to the country + medal combinations with the highest counts.

    library(tidyverse)
    
    London_ordered <- London.melt %>%
      mutate(id = paste(country, medal.type, sep = "_") %>%
               as_factor() %>%
               fct_reorder(count, .fun = min))
    
    levels(London_ordered$id) %>% tail()
    #> [1] "Great Britain & N. Ireland_gold" "United States_silver"           
    #> [3] "United States_bronze"            "Russian Federation_bronze"      
    #> [5] "China_gold"                      "United States_gold"
    

    Then use this ID as your y-axis. On its own, you'd then have very long labels that include the medal type. Because of the unique delimiter, you can write an inline function for the y-axis labels that will remove the delimiter and any word characters that come after it, leaving you with just the countries. Moving the facet specification to a facet_wrap function lets you then set the free y-scale.

    qplot(x = count, y = id, data = London_ordered, geom = "point") +
      scale_y_discrete(labels = function(x) str_remove(x, "_\\w+$")) +
      facet_wrap(~ medal.type, scales = "free_y", ncol = 1)
    

提交回复
热议问题