R 使用S3类生成ggplot

R 使用S3类生成ggplot,r,class,ggplot2,R,Class,Ggplot2,我一直在努力学习如何使用S3类结构,但在plot函数中使用ggplot时遇到了一些困难。我有一些测试数据: testdata = data.frame(col1 = rnorm(100), col2 = rnorm(100)) testdata = structure(list(testdata = testdata), class = "test") 然后我有我的绘图函数: plot.test = function (x, y, data) { data = data$testdata

我一直在努力学习如何使用S3类结构,但在plot函数中使用ggplot时遇到了一些困难。我有一些测试数据:

testdata = data.frame(col1 = rnorm(100), col2 = rnorm(100))
testdata = structure(list(testdata = testdata), class = "test")
然后我有我的绘图函数:

plot.test = function (x, y, data)
{ 
  data = data$testdata
  ggplot(data = data, aes_string(x = x, y = y)) + geom_point()
}
所以我想通过使用plot而不是plot.test来使用这个函数。如果我使用plot.test并为函数指定x和y列,则该函数有效:

plot.test(x = 'col1', y = 'col2', data = testdata)
但是,当我仅使用plot时,会出现一个错误:

plot(x = 'col1', y = 'col2', data = testdata)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf
5: In min(x) : no non-missing arguments to min; returning Inf
6: In max(x) : no non-missing arguments to max; returning -Inf
7: In plot.window(...) : "data" is not a graphical parameter

我显然在某个地方缺少一些S3类的知识…

我发现,如果我将plot.test更改为autoplot.test,那么只要我更改变量的顺序,这种方法就行了:

testdata = data.frame(col1 = rnorm(100), col2 = rnorm(100))
testdata = structure(list(testdata = testdata), class = "test")
autoplot.test = function (x, y, data)
{ 
  data = data$testdata
  ggplot(data = data, aes_string(x = x, y = y)) + geom_point()
}
autoplot.test(testdata, x = 'col1', y = 'col2') ## works
autoplot(testdata, x = 'col1', y = 'col2') ## also works
我想我需要autoplot,因此可能已经回答了我自己的问题。