Ordering factors in each facet of ggplot by y-axis value

后端 未结 1 1316
后悔当初
后悔当初 2020-12-11 22:51

Lets say, in R, I have a data frame letters, numbers and animals and I want to examine the relationship between all three graphically. I could do something like.

<         


        
1条回答
  •  时光说笑
    2020-12-11 23:20

    I've found dplyr doesn't work super well with group_by() when dealing with different factor levels in each of the groups. So one work around is thinking of creating a new factor that's unique for each animal-letter combination and ordering that. First, we create an interaction variable with animal+letter and determine the proper order for each of the letters for the animals

    new_order <- my_df %>% 
      group_by(animals) %>% 
      do(data_frame(al=levels(reorder(interaction(.$animals, .$letters, drop=TRUE), .$numbers)))) %>% 
      pull(al)
    

    Now we create the interaction variable in the data we want to plot, use this new ordering, and finally change the labels so they look like just the letters again

    my_df %>% 
      mutate(al=factor(interaction(animals, letters), levels=new_order)) %>%
      ggplot(aes(x = al, y = numbers)) +
        geom_point() + facet_wrap(~animals, ncol = 1, scales = 'free_x') +
        scale_x_discrete(breaks= new_order, labels=gsub("^.*\\.", "", new_order))
    

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