我想构建一个函数,它接受一个df并生成ggplot2条形图,条形排序,其中x轴值按其y值按降序排序。特别是,我会在循环中传递数据帧(使用purrr包中的map函数)
#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)
首先,我将带有map的每个数据帧传递给函数,该函数对因子进行排序&#34; COU&#34;在每个数据框中,然后我将它传递给ggplot2,忽略排序
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()
})