简体   繁体   中英

reordering geom_bar by a specific variable with facet wrap

My data is the following:

   ID    name      value
   <chr> <chr>     <dbl>
 1 GDX   B     -0.174   
 2 GDX   A      0.00112 
 3 XLF   B      1.25    
 4 XLF   A      0.000657
 5 IAU   B     -0.426   
 6 IAU   A      0.000613

I am trying to use ggplot to rearrange my plots based only on A values. My current code reorders the data based on A and B values:

x %>%  
 ggplot(aes(x = reorder(ID, -value), y = value)) +
  geom_bar(stat = "identity") +
  facet_wrap(~name, scales = "free")

I would like to order the data only be A .

x <- structure(list(ID = c("GDX", "GDX", "XLF", "XLF", "IAU", "IAU", 
"GLD", "GLD", "TLT", "TLT", "XLU", "XLU", "DIA", "DIA", "LQD", 
"LQD", "XLK", "XLK", "VGT", "VGT"), name = c("B", "A", "B", "A", 
"B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B", 
"A", "B", "A"), value = c(-0.174020403482165, 0.00111703027471891, 
1.24702139367257, 0.000657161160802596, -0.426268548277023, 0.000612940148515207, 
-0.413513856705566, 0.000600042013460591, -0.388416572490298, 
0.000403605285171551, 0.332656822608043, 0.000339546362101647, 
0.913431089476471, 0.000309545750009797, -0.0348619751363881, 
0.000276487954168884, 1.10293107347112, 0.000267740303325635, 
1.18495447176302, 0.000246175277484366)), row.names = c(NA, -20L
), class = c("tbl_df", "tbl", "data.frame"))

You can reorder the factor levels before calling ggplot:

x %>% 
    mutate(ID = factor(ID, levels = x %>% filter(name == "A") %>% arrange(desc(value)) %>% pull(ID))) %>%
  ggplot(aes(x = ID, y = value)) +
  geom_bar(stat = "identity") +
  facet_wrap(~name, scales = "free")

Here is a slightly more complicated reorder where instead of taking the mean of all values for the group, we set all the B values to -Inf and just sort by the max A value.

x %>%  
  ggplot(aes(x = reorder(ID, if_else(name=="A",value,-Inf), FUN=max), y = value)) +
  geom_bar(stat = "identity") +
  facet_wrap(~name, scales = "free")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM