Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scatter.smooth R function - color

Tags:

plot

r

How can I change the color of the scatter.smooth in R? I can add a "col" parameter, but that only changes the color of the data points (the dots), not the actual line that is on the screen. How do I change the color of the actual line.

like image 575
CodeGuy Avatar asked Sep 30 '11 05:09

CodeGuy


2 Answers

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:

enter image description here

like image 107
Gavin Simpson Avatar answered Sep 28 '22 03:09

Gavin Simpson


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')
like image 23
Oscar Perpiñán Avatar answered Sep 28 '22 02:09

Oscar Perpiñán