Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call reorder within aes_string of ggplot

Tags:

r

ggplot2

I need to reorder a barplot from high to low (left to right) using ggplot & aes_string(). For e.g. for a 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 column numbers of the dataframe instead of column names as shown below

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

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

How can I use the re-order function within aes_string to achieve this?

like image 916
Tinniam V. Ganesh Avatar asked May 16 '17 10:05

Tinniam V. Ganesh


2 Answers

With the latest version of ggplot, you should be use aes with !! and sym() to turn your strings into symbols.

ggplot(top10, 
  aes(
    x = reorder(!!sym(colnames(top10)[num1]), meanFeat),
    y = meanFeat, 
    fill = !!sym(colnames(top10)[num1]))) +  
  geom_col()

or using the .data pronoun

ggplot(top10, 
  aes(
    x = reorder(.data[[ colnames(top10)[num1] ]], meanFeat),
    y = meanFeat, 
    fill = .data[[ colnames(top10)[num1] ]])) +  
  geom_col()
like image 111
MrFlick Avatar answered Nov 03 '22 11:11

MrFlick


Since 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")
like image 14
Erdem Akkas Avatar answered Nov 03 '22 11:11

Erdem Akkas