scatter.smooth R function - color
There is no need to hack scatter.smooth()
to achieve the desired result. Notice on ?scatter.smooth
that there is another function documented; loess.smooth()
. This latter function is used by scatter.smooth()
to compute the x an y coordinates of the fitted loess smoother. The desired plot can be produced by two calls; i) to plot()
, and ii) a second call to loess.smooth()
to draw the line.
Using @Andrie's example, this would be:
plot(dist ~ speed, data = cars, col = "blue")
with(cars, lines(loess.smooth(speed, dist), col = "green"))
The loess.smooth()
step returns a list with x
and y
components that can be plotted easily using 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
The plot produced looks like this:
As an alternative, you can use lattice::xyplot
with type=c('p', 'smooth')
:
xyplot(dist~speed, data=cars, type=c('p', 'smooth'), col.line='green')
If you read the source code for scatter.smooth
, you'll find that the prediction line is plotted without a col
parameter.
This means you will have to modify the code. Here I add a lcol
argument for line colour:
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"))