2014-10-30 67 views
0

我一直在努力学习如何使用S3类结构,并且我试图在绘图函数中使用ggplot遇到了一些困难。我有一些测试数据:使用S3类生成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的一些知识班某处...

+0

我想我需要'autoplot',因此也许可以回答我自己的问题。 – nathaneastwood 2014-10-30 09:26:59

回答

0

我已经想通了,如果我改变plot.testautoplot.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