【问题标题】:ggplot2 fails inside a function [duplicate]ggplot2在函数内失败[重复]
【发布时间】:2014-11-15 19:25:16
【问题描述】:

我在尝试用 ggplot() 编写一些函数时遇到了麻烦。

这是我正在尝试做的简化版本。 这按预期工作:

testdata <- matrix(1:10, 
                   nrow = 5)
ggplot() + geom_point(aes(testdata[,1], 
                          testdata[,2]))

将相同的代码放入函数中:

mygg <- function(data){
  ggplot() + geom_point(aes(data[,1], 
                            data[,2]))
}
mygg(testdata)  

给出错误:

Error in data[, 1] : object of type 'closure' is not subsettable

当我用aes_string 替换aes 时,只绘制矩阵的第一行。

当我重命名我的矩阵“数据”时它确实有效,但重点是我想绘制一堆具有不同名称的矩阵。

我已尽力搜索论坛,发现我的问题基本上是重复的,但我完全无法找到解决我的具体问题的方法。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我玩了一分钟,发现你需要在aes() 方法中使用变量名。此外,我将矩阵强制转换为数据框,因为 ggplot 也对此有所抱怨。

    复制问题,显示导致解决方案的输出。

    > mygg(testdata)
    Error in data[, 1] : object of type 'closure' is not subsettable
    > testdata
      V1 V2
    1  1  6
    2  2  7
    3  3  8
    4  4  9
    5  5 10
    > testdata <- matrix(1:10, nrow = 5)
    > testdata <- as.data.frame(testdata)
    > mygg <- function(data){
    +   ggplot(data) + geom_point(aes(x = V1, y = V2))
    + }
    > mygg(testdata)
    > # outputs the plot
    

    更漂亮的代码

    library('ggplot2')
    testdata <- matrix(1:10, nrow = 5)
    testdata <- as.data.frame(testdata)
    mygg <- function(data){
      ggplot(data) + geom_point(aes(x = V1, y = V2))
    }
    mygg(testdata)
    

    一般来说,您需要使您的函数足够灵活,以考虑变量名称等内容(可能使用names() 函数)。

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2020-09-07
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多