2011-09-30 53 views
3

如何更改R中scatter.smooth的顏色?我可以添加一個「col」參數,但這隻會改變數據點(點)的顏色,而不會改變屏幕上的實際線條。如何更改實際線條的顏色。scatter.smooth R函數 - 顏色

回答

9

無需破解scatter.smooth()實現預期的結果。關於?scatter.smooth的通知,說明有另外的功能; loess.smooth()。後一個函數由scatter.smooth()用來計算擬合黃土平滑器的x和y座標。所需的情節可以通過兩次調用產生; i)至plot(),以及ii)第二次致電loess.smooth()來劃定界限。

使用@ Andrie的例子,這將是:

plot(dist ~ speed, data = cars, col = "blue") 
with(cars, lines(loess.smooth(speed, dist), col = "green")) 

loess.smooth()步驟返回與可以繪製xy組件列表容易使用lines()

> with(cars, loess.smooth(speed, dist)) 
$x 
[1] 4.000000 4.428571 4.857143 5.285714 5.714286 6.142857 
[7] 6.571429 7.000000 7.428571 7.857143 8.285714 8.714286 
[13] 9.142857 9.571429 10.000000 10.428571 10.857143 11.285714 
[19] 11.714286 12.142857 12.571429 13.000000 13.428571 13.857143 
[25] 14.285714 14.714286 15.142857 15.571429 16.000000 16.428571 
[31] 16.857143 17.285714 17.714286 18.142857 18.571429 19.000000 
[37] 19.428571 19.857143 20.285714 20.714286 21.142857 21.571429 
[43] 22.000000 22.428571 22.857143 23.285714 23.714286 24.142857 
[49] 24.571429 25.000000 

$y 
[1] 4.962236 6.132561 7.294531 8.451282 9.605949 10.761666 
[7] 11.921569 13.088792 14.266472 15.457742 16.646268 17.788187 
[13] 18.916270 20.068806 21.284085 22.534880 23.776272 25.020014 
[19] 26.277859 27.554763 28.793605 30.039834 31.287544 32.541662 
[25] 33.982881 35.706712 37.262771 38.683122 40.080683 41.491404 
[31] 42.951233 44.438569 45.860202 47.361200 49.023137 50.730452 
[37] 52.619626 54.852390 57.325596 59.936095 62.580738 65.156375 
[43] 67.559859 69.876282 72.248492 74.659973 77.094212 79.534692 
[49] 81.964898 84.368316 

情節制作的外觀像這樣:

enter image description here

+1

+1比我的更好的解決方案 – Andrie

3

如果您閱讀scatter.smooth的源代碼,您會發現預測行是繪製的,沒有col參數。

這意味着你將不得不修改代碼。在這裏我想補充一個lcol論據線顏色:

scatter.smooth <- function (x, y = NULL, span = 2/3, degree = 1, 
    family = c("symmetric", "gaussian"), xlab = NULL, ylab = NULL, 
    ylim = range(y, prediction$y, na.rm = TRUE), evaluation = 50, lcol="red", ...) 
{ 
    xlabel <- if (!missing(x)) 
     deparse(substitute(x)) 
    ylabel <- if (!missing(y)) 
     deparse(substitute(y)) 
    xy <- xy.coords(x, y, xlabel, ylabel) 
    x <- xy$x 
    y <- xy$y 
    xlab <- if (is.null(xlab)) 
     xy$xlab 
    else xlab 
    ylab <- if (is.null(ylab)) 
     xy$ylab 
    else ylab 
    prediction <- loess.smooth(x, y, span, degree, family, evaluation) 
    plot(x, y, ylim = ylim, xlab = xlab, ylab = ylab, ...) 
    lines(prediction, col=lcol) # <<-- Note the edit here 
    invisible() 
} 

with(cars, scatter.smooth(speed, dist, col="blue", lcol="green")) 

enter image description here

4

作爲替代方案,可以使用lattice::xyplottype=c('p', 'smooth')

xyplot(dist~speed, data=cars, type=c('p', 'smooth'), col.line='green')