R 使用索引而不是名称指定列

R 使用索引而不是名称指定列,r,ggplot2,plot,R,Ggplot2,Plot,我编写了一个函数,使用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 = eleme

我编写了一个函数,使用
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)
}

PropBarPlot正如@baptiste所指出的,在定义x和y值时,应该使用
aes_string()
而不是
aes()
来使用字符串。您还应该将
变量
放在引号内

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)
}

propbarplot可能是重复的,但请尝试
aes_string(names(df)[1])
@baptiste错误:无法将类“uneval”强制转换为数据。如果没有包含数据的可复制示例,很难判断
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)
}