【问题标题】:ggplot resulting in error in function but working fine outsideggplot导致功能错误但在外面工作正常
【发布时间】: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=colx=my_df$colx=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


【解决方案1】:

您的问题是 []aes() 参数中不起作用

这应该有效:

MyData <- mtcars #Just to gain some reproducibility in the example. 

myfunc   <- function(my_df,colmn) {
 if (lapply(my_df[colmn], is.numeric) == TRUE){
   print(class(my_df[colmn])) 
   print(colmn) 

   #Create an additional object to store your variables
   DataTemp <- data.frame(my_df[colmn], my_df["mpg"])
   names(DataTemp) <- c("X", "Y")

#Plot the scatter plot using the created object
ggplot(data = DataTemp,
       aes(x = X, 
           y = Y )) +
  geom_point(size=2) }}

myfunc(my_df = MyData, colmn="gear")

【讨论】:

    猜你喜欢
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 2014-02-06
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2011-04-09
    相关资源
    最近更新 更多