用索引而不是名称指定列 [英] Specifying column with its index rather than name
本文介绍了用索引而不是名称指定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了一个函数,该函数使用 ggplot
函数获取比例堆积条形图.现在,我在此 ID
中使用列名.
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??
谢谢.
推荐答案
@baptiste指出,您应该使用 aes_string()
而不是 aes()
来使用定义x和y值的字符串.另外,您还应该在引号中放入 value
和 variable
.
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)
}
这篇关于用索引而不是名称指定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文