I have followed this example: re-ordering factors according to a value using fct_reorder in R
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
plot_data = top5_producers %>%
group_by(source_crop) %>%
arrange(source_crop, FC_imports) %>%
mutate(order = row_number())
plot_data %>%
ggplot(aes(y = FC_imports, x = country, fill = source_crop)) +
geom_bar(stat="identity") +
facet_wrap(~source_crop, scales = "free") +
scale_x_discrete(breaks = plot_data$order, labels = plot_data$country) +
coord_flip()
This is my output
I want bars to be sorted from within each group, but I can't get the code to work. What am I doing wrong?