R 将可变列索引传递给 ggplot2 [英] R pass variable column indices to ggplot2

查看:26
本文介绍了R 将可变列索引传递给 ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将列索引作为我将重复使用的函数的一部分传递给 ggplot.喜欢:

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

我将始终使用第一列作为我的 x 变量,第二列作为我的 y 变量,但列名在数据集之间会发生变化.我已经搜遍了.. 有什么想法吗?

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?

这是我使用的答案:

require(ggplot2)

myplot <- function(df){
   ggplot(df, aes_string(colnames(df)[1], colnames(df)[2])) + geom_point()
}

推荐答案

您可以使用 aes_string 代替 aes 来传递字符串而不是使用对象,即:

You can use the aes_string in stead of aes 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆