我在R中编写了一个函数,它从所述数据框中读取data.frame
和两个列名,然后生成一个散点图。我想修改我的函数,以便不是简单地生成绘图,而是创建一个ggplot对象,然后我可以修改它。这是我的功能:
my_scatter = function (x,a,b) {
test1 = class(x)
if (! test1 == "data.frame") {
stop("1st Variable should be a data frame")
}
test2 = class(x[,a])
valid_classes = c("integer", "numeric")
if (! test2 %in% valid_classes) {
stop("2nd Variable should either be an integer or numeric")
}
test3 = class(x[,b])
if (! test3 %in% valid_classes) {
stop("3rd Variable should either have class numeric or integer")
}
plot(x[,a],x[,b], main = paste(a, "vs", b), xlab = a, ylab = b)
p = ggplot(data = x, aes(a, b)) + geom_point() + geom_abline(slope = 1, intercept = 0, color = "white")
return(p)
}
请注意,传递给函数时必须引用变量a
和b
,如下所示:
test_obj = my_scatter(df, "Age", "Income")
此函数自动生成一个简单的散点图,看起来应该完全正确。 ggplot
代码生成一个带有以下内容的图:
abline
如果我直接在控制台中运行相同的ggplot
代码,它的工作原理应该是我将变量a
和b
替换为实际的列名:
p = ggplot(data = x, aes(Age, Income)) + geom_point() + geom_abline(slope = 1, intercept = 0, color = "white")
print(p)
如果我将变量定义为插入ggplot调用,它就会以与函数中相同的方式失败:
a = "Age"
b = "Income"
p = ggplot(data = x, aes(a, b)) + geom_point() + geom_abline(slope = 1, intercept = 0, color = "white")
print(p)
我认为我的问题与我在函数中传递数据的方式有关,并尝试删除这样的引号:
...
A = gsub("\"", "", a)
B = gsub("\"", "", b)
p = ggplot(data = x, aes(A, B)) + geom_point() + geom_abline(slope = 1, intercept = 0, color = "white")
return(p)
}
并且像这样:
...
a = substitute(a)
b = substitute(b)
plot(x[,a],x[,b], main = paste(a, "vs", b), xlab = a, ylab = b)
p = ggplot(data = x, aes_q(a, b)) + geom_point() + geom_abline(slope = 1, intercept = 0, color = "white")
return(p)
}
没有明显的效果。