R:ggplot指定列的索引而不是名称

Rac*_*wal 7 plot r ggplot2 dataframe

我编写了一个函数来使用ggplot函数获得比例堆积条形图.现在我在这里使用列名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)
}
Run Code Online (Sandbox Code Playgroud)

我想让它变得通用.所以我想使用列索引而不是列名.我尝试过做这样的事情.

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)
}
Run Code Online (Sandbox Code Playgroud)

但没有用.谁能建议我怎么做?

谢谢.

Did*_*rts 7

正如@baptiste你应该使用中指出aes_string(),而不是aes()在定义x和y的值使用字符串.你也应该把valuevariable放在引号内.

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)
}
Run Code Online (Sandbox Code Playgroud)