【发布时间】:2020-01-13 19:18:21
【问题描述】:
myfunc <- function(my_df,colmn) {
if (lapply(my_df[colmn], is.numeric) == TRUE){
print(class(my_df[colmn])) #Checking to see if I'm getting dataframe
print(colmn) #Check to see if I'm getting the right column
#Plotting a scatter plot
ggplot(data=my_df,
aes(x =my_df[colmn], #x-axis being the input colmn value via the function
y=my_df["colmn2"] # a column that is already present in the my_df dataframe
)
) +
geom_point(size=2)
}
}
myfunc(my_df=a_df, colmn="colmn1")
输出 -
[1] "data.frame"
[1] "colmn1"
错误 -
不知道如何为对象类型自动选择比例 数据帧。默认为连续。不知道怎么自动 为 data.frame 类型的对象选择比例。默认为连续。 is.finite(x) 中的错误:未为类型“列表”实现默认方法
如果我在函数之外执行 ggplot(如下代码),我会得到漂亮的散点图而没有任何错误
ggplot(data=a_df, aes(x=a_df$colmn1,y=a_df$colmn2)) + geom_point(size=2)
我不确定为什么这些值默认为连续的以及为什么 is.finite(x) 出现
编辑 - 我尝试了 aes() 中的 x=col、x=my_df$col 和 x=my_df[col] 格式
【问题讨论】:
-
在 aes 函数中,您不需要重复数据框名称,因为它已经在 data= 参数中指定。你试过 aes(x=colmn, ...) 吗?
-
尝试使用
aes_string()、aes_string(x = colmn, y = "colmn2")传递字符串(不参考数据集)或使用.data代词(使用来自rlang 的tidyeval)、aes(x = .data[[colmn]], y = .data[["colmn2"]]))。aes_string()是在函数中使用 ggplot2 的“旧方式”,我相信它现在已被弃用,取而代之的是 tidyeval。 -
还有其他与此相关的问题/答案,但this one 是我在搜索“函数中的 r ggplot2”时发现的最新问题。
标签: r function ggplot2 scatter-plot