2013-04-24 35 views
4

我已经写了一个函数来获取使用ggplot函数的比例堆积条形图。现在我在这个ID中使用列名。R:ggplot指定列与其索引而不是名称

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

但没用。有人可以建议我如何做到这一点?

谢谢。

+0

可能重复,但尝试'aes_string(名称(DF)[1])' – baptiste 2013-04-24 08:30:41

+0

@baptiste错误:不能强迫类的 “uneval”'成data.frame – 2013-04-24 08:33:36

+0

很难说没有一个可重复包括数据的例子 – baptiste 2013-04-24 08:37:42

回答

6

正如@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) 
} 
相关问题