14

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.

4

2 に答える 2

13

@baptiste で指摘されているように、x 値と y 値の定義に文字列を使用するaes_string()代わりに使用する必要があります。aes()また、引用符で囲む必要がvalueありvariableます。

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)
}
于 2013-04-24T08:48:11.353 に答える