I would like to build a function which takes a df and generates ggplot2 barplots with the bars sorted, where the x-axis values are sorted in desceding order by their y-values. Especially, I would pass the data frames in a loop (using the map function from the purrr package)
#Example Data
df1=as.data.frame(cbind(COU=rbind("CHN","ITA","JPN","KOR","USA"), val=rbind(0.80,0.40,0.30,0.32,0.21)))
names(df1)<-c("COU","17t19")
df2=as.data.frame(cbind(COU=rbind("DEU","FRA","GBR","ITA","USA"),val= rbind(0.70,0.60,0.20,0.52,0.31)))
names(df2)<-c("COU","20t22")
top_5=list(df1,df2)
First, I pass each data frame with map to the function, which sorts the factor "COU" in each data frame and then I pass it to ggplot2, which ignores the sorting
library(purrr)
library(ggplot2)
map(.x=top_5,.f=function(df){
name.x.2<-names(df)[2]
names(df)[2]<-"order.var"
df$order.var<-as.numeric(paste(df$order.var))
df<-df[order(df$order.var,decreasing =T), ]
names(df)[2]<-name.x.2
ggplot(df, aes_q(x = as.name(names(df)[1]),
y = as.name(names(df)[2]), fill=as.name(names(df)[1]))) +
geom_bar(stat="identity", position="dodge", colour="black")+
theme_bw()
})