R将变量列索引传递给ggplot2 [英] R pass variable column indices to ggplot2
本文介绍了R将变量列索引传递给ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将列索引传递给ggplot,作为我将重复使用的函数的一部分。
like:
myplot< - function(df){
ggplot(df,aes [,1],df [,2]))+ geom_point()
}
我将永远使用第一列作为我的x变量,第二列作为我的y变量,但列名在数据集之间变化。我搜索过了..任何想法?
编辑:
这是答案我使用:
require(ggplot2)
/ pre>
myplot< - function ){
ggplot(df,aes_string(colnames(df)[1],colnames(df)[2]))+ geom_point()
}
解决方案您可以使用
aes_string
代替aes
传递字符串代替使用对象,即:myplot = function (df,x_string,y_string){
ggplot(df,aes_string(x = x_string,y = y_string))+ geom_point()
}
myplot(df,A,B )
myplot(df,B,A)
I'm attempting to pass the column indices to ggplot as part of a function I'll be using repeatedly. like:
myplot <- function(df){ ggplot(df, aes(df[, 1], df[, 2])) + geom_point() }
I'll always be using the first column as my x variable and the second column as my y-variable, but the column names change between data sets. I've searched all over.. Any ideas?
EDIT:
This is the answer I used:
require(ggplot2) myplot <- function(df){ ggplot(df, aes_string(colnames(df)[1], colnames(df)[2])) + geom_point() }
解决方案You can use the
aes_string
in stead ofaes
to pass string in stead of using objects, i.e.:myplot = function(df, x_string, y_string) { ggplot(df, aes_string(x = x_string, y = y_string)) + geom_point() } myplot(df, "A", "B") myplot(df, "B", "A")
这篇关于R将变量列索引传递给ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文