0

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()
 })
S.K.
  • 365
  • 1
  • 3
  • 17
  • 1
    Don't do `data.frame(cbind(...))`. You're coercing everything to a matrix, which only has one type, and then to data.frame, which can handle multiple; as a result all your data becomes factors, which will surely cause problems. Just use `data.frame` by itself, wrapping each vector inside in `c`. Also, it's generally inadvisable to name variables things starting with numbers in R; you'll have to use a lot of backticks to make it work. – alistaire Dec 04 '16 at 21:19
  • Thanks for the comment. Okay these aspects aside my problem is that ggplot2 does not recognize the ordering of the factor and I cant see a fix to this. – S.K. Dec 05 '16 at 11:51

0 Answers0