1

I originally asked this question but it was marked as a duplicate and that I should follow this solution How to order bars within all facets?.

Here is a dput of my top5_producers variable

structure(list(iso3_code = c("BGD", "CHN", "CHN", "CHN", "DEU", 
"EGY", "IDN", "IDN", "IND", "IND", "JPN", "KOR", "MEX", "MEX", 
"MMR", "NLD", "NLD", "PAK", "VNM", "VNM"), country = c("Bangladesh", 
"China", "China", "China", "Germany", "Egypt", "Indonesia", "Indonesia", 
"India", "India", "Japan", "South korea", "Mexico", "Mexico", 
"Myanmar", "Netherlands", "Netherlands", "Pakistan", "Viet Nam", 
"Viet Nam"), source_crop = c("Sugar cane", "Oil palm fruit", 
"Soybeans", "Sugar cane", "Oil palm fruit", "Maize", "Soybeans", 
"Sugar cane", "Oil palm fruit", "Sugar cane", "Maize", "Maize", 
"Maize", "Soybeans", "Sugar cane", "Oil palm fruit", "Soybeans", 
"Oil palm fruit", "Maize", "Soybeans"), FC_imports = c(1949020L, 
5457164L, 84505368L, 3062047L, 2201599L, 8652235L, 6311197L, 
4761885L, 8335597L, 2119435L, 15342352L, 9804926L, 14217581L, 
6540675L, 2205780L, 3867813L, 7534711L, 2817298L, 8228098L, 6273590L
)), row.names = c(NA, -20L), .internal.selfref = <pointer: 0x7f953580b2e0>, class = c("tbl_df", 
"tbl", "data.frame"))

Here is my code

scale_x_reordered <- function(..., sep = "___") {
    reg <- paste0(sep, ".+$")
    ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)
  }

reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
  new_x <- paste(x, within, sep = sep)
  stats::reorder(new_x, by, FUN = fun)
}

plot_data = top5_producers %>% 
  group_by(source_crop) %>% 
  arrange(source_crop, FC_imports) %>% 
  mutate(order = row_number())

plot_data %>%  
  ggplot(aes(reorder_within(country, FC_imports, source_crop), FC_imports)) +
  geom_bar(stat="identity") +
  coord_flip() +
  scale_x_reordered() +
  facet_wrap(~source_crop, scales = "free") +
  theme(axis.text.x=element_text(angle=90,hjust=1,vjust=.5,colour='gray50'))

My output is

enter image description here

As you can see the values on the x-axis disappeared and there is text added to the y-values (compare to the image in the original question linked above). I honestly don't know what to make of this and would appreciate some help. I would like the bars in each facet to have different colours and that they should be ordered within each facet.

Session info:

R version 3.6.1 (2019-07-05)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Catalina 10.15.3

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] tmap_2.2            rnaturalearth_0.1.0 strucchange_1.5-2   sandwich_2.5-1      zoo_1.8-6          
 [6] WDI_2.6.0           ggpubr_0.2.3        magrittr_1.5        segmented_1.0-0     scales_1.0.0       
[11] spData_0.3.0        countrycode_1.1.0   janitor_1.2.0       data.table_1.12.2   forcats_0.4.0      
[16] stringr_1.4.0       dplyr_0.8.3         purrr_0.3.3         readr_1.3.1         tidyr_1.0.0        
[21] tibble_2.1.3        ggplot2_3.2.1       tidyverse_1.2.1    

loaded via a namespace (and not attached):
 [1] nlme_3.1-140       satellite_1.0.1    sf_0.7-4           lubridate_1.7.4    webshot_0.5.1     
 [6] RColorBrewer_1.1-2 httr_1.4.0         SnowballC_0.6.0    mapview_2.7.0      tools_3.6.1       
[11] backports_1.1.5    utf8_1.1.4         rgdal_1.4-3        R6_2.4.1           KernSmooth_2.23-15
[16] rgeos_0.4-3        DBI_1.0.0          lazyeval_0.2.2     colorspace_1.4-1   raster_2.8-19     
[21] withr_2.1.2        sp_1.3-1           tidyselect_0.2.5   leaflet_2.0.2      compiler_3.6.1    
[26] cli_1.1.0          rvest_0.3.3        xml2_1.2.0         labeling_0.3       classInt_0.3-3    
[31] digest_0.6.21      base64enc_0.1-3    dichromat_2.0-0    pkgconfig_2.0.3    htmltools_0.4.0   
[36] htmlwidgets_1.5.1  rlang_0.4.2        readxl_1.3.1       rstudioapi_0.10    shiny_1.3.2       
[41] generics_0.0.2     jsonlite_1.6       crosstalk_1.0.0    tokenizers_0.2.1   Matrix_1.2-17     
[46] fansi_0.4.0        Rcpp_1.0.3         munsell_0.5.0      lifecycle_0.1.0    stringi_1.4.3     
[51] RJSONIO_1.3-1.1    tmaptools_2.0-1    grid_3.6.1         promises_1.0.1     crayon_1.3.4      
[56] lattice_0.20-38    haven_2.1.0        splines_3.6.1      hms_0.5.1          zeallot_0.1.0     
[61] pillar_1.4.2       ggsignif_0.6.0     stats4_3.6.1       codetools_0.2-16   XML_3.98-1.20     
[66] glue_1.3.1         tidytext_0.2.2     modelr_0.1.4       png_0.1-7          vctrs_0.2.0       
[71] httpuv_1.5.1       cellranger_1.1.0   gtable_0.3.0       assertthat_0.2.1   mime_0.6          
[76] lwgeom_0.1-7       xtable_1.8-4       broom_0.5.2        e1071_1.7-1        janeaustenr_0.1.5 
[81] later_0.8.0        class_7.3-15       viridisLite_0.3.0  units_0.6-3        ellipsis_0.3.0    
[86] spDataLarge_0.3.1 
Robin Lindström
  • 622
  • 4
  • 15
  • 1
    Can you please post your sessionInfo()? I have run this locally and appeared to get the results that you want, might have something to do with package versions, but I'm checking the rest – Yuri-M-Dias Mar 02 '20 at 21:00
  • I have added session info, but the solution that Stefan posted below worked fine and it is much cleaner since it uses a package. – Robin Lindström Mar 03 '20 at 03:54

1 Answers1

1

tidytext::reorder_within and tidytext::scale_x_reordered should do the trick:

plot_data %>%  
  ungroup() %>% 
  mutate(country = tidytext::reorder_within(
    country, FC_imports, source_crop)) %>% 
  ggplot(aes(x = country, y = FC_imports, fill = source_crop)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~source_crop, scales = "free_y") +
  coord_flip() +
  tidytext::scale_x_reordered()

See the blog post by Julia Silge.

stefan
  • 90,330
  • 6
  • 25
  • 51