Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying column with its index rather than name

Tags:

plot

r

ggplot2

I have written a function to get the Proportional Stacked Bar plot using ggplot function. Right now I am using Column name in this ID.

PropBarPlot<-function(df, mytitle=""){
    melteddf<-melt(df, id="ID", na.rm=T)
    ggplot(melteddf, aes(ID, value, fill=variable)) + 
      geom_bar(position="fill") + 
      theme(axis.text.x = element_text(angle=90, vjust=1)) + 
      labs(title=mytitle)
}

I want to make it generic. So I want to make use of column index instead of column name. I tried doing something like this.

PropBarPlot<-function(df, mytitle=""){
    melteddf<-melt(df, id=names(df)[1], na.rm=T)
    ggplot(melteddf, aes(names(df)[1], value, fill=variable)) + 
      geom_bar(position="fill") + 
      theme(axis.text.x = element_text(angle=90, vjust=1)) + 
      labs(title=mytitle)
}

But of no use. Can someone suggest me how to do this??

Thanks.

like image 876
Rachit Agrawal Avatar asked Apr 24 '13 08:04

Rachit Agrawal


People also ask

How do I select a column by index in R?

By using the R base df[] notation or select() function from dplyr package you can select a single column or select multiple columns by index position (column number) from the R Data Frame.

How do you access a DataFrame column by index?

Use DataFrame. loc[] and DataFrame. iloc[] to select a single column or multiple columns from pandas DataFrame by column names/label or index position respectively. where loc[] is used with column labels/names and iloc[] is used with column index/position.


1 Answers

As pointed out by @baptiste you should use aes_string() instead of aes() to use strings in defining x and y values. Also you should put value and variable inside quotes.

PropBarPlot<-function(df, mytitle=""){
  melteddf<-melt(df, id=names(df)[1], na.rm=T)
  ggplot(melteddf, aes_string(x=names(df)[1],y= "value", fill="variable")) + 
    geom_bar(position="fill") + 
    theme(axis.text.x = element_text(angle=90, vjust=1)) + 
    labs(title=mytitle)
}
like image 94
Didzis Elferts Avatar answered Nov 11 '22 12:11

Didzis Elferts