How to reorder call in aes_string ggplot

I need to reorder the barplot from high to low (left to right) using ggplot and aes_string (). Ex. for dataframe df <- f (X, Y, Z) this can be done with

 ggplot(top10,aes(x=reorder(X,-Y),y=Y,fill=X) + geom_bar(stat="identity")

      

But I need to achieve this by referring to the column numbers of the data block instead of the column names as shown below

 ggplot(top10, aes_string(x=colnames(top10)[num1],y=meanFeat, 
 fill=colnames(top10)[num1])) +  geom_bar(stat="identity")

      

The above statement outputs the result using column numbers. However, it does not reorder from high to low (left to right)

How can I use the reorder function within aes_string to do this?

+5


source to share


2 answers


Since it aes_string

works with strings, use paste

:



ggplot(top10, aes_string(x=paste0("reorder(",colnames(top10)[num1],", -Y)"),y=meanFeat,
 fill=colnames(top10)[num1])) +  geom_bar(stat="identity")

      

+8


source


With the latest version of ggplot, you must use aes

with !!

and sym()

to turn your strings into characters.



ggplot(top10, 
  aes(
    x = reorder(!!sym(colnames(top10)[num1]), meanFeat),
    y = meanFeat, 
    fill=!!sym(colnames(top10)[num1]))) +  
  geom_bar(stat="identity")

      

0


source







All Articles