Data visualization in R: Add smooth curve and shaded area to a plot

Within this article I want to show you an easy way to add a smooth curve to your plot, create an area around this curve and fill the area with a transparent color.

Let’s start with a standard plot.

x <- 1:20
y <- c(29,33,91,88,77,110,157,185,138,189,201,205,187,177,168,201,222,278,270,285)
plot(x,y)

R28_a

At first we will add a smooth curve. This can be done by using the loess function which calculates the local polynomial regression fitting. Based on this polynomial regression we can predict the values for our plot and draw them ass additional line. Within the loess function I have used the span property to define the degree of smoothing.

x <- 1:20
y <- c(29,33,91,88,77,110,157,185,138,189,201,205,187,177,168,201,222,278,270,285)
plot(x,y)

lo <- loess(y~x, span = 1.5)
pr <- predict(lo)
lines(pr, lwd=2)
 

R28_b

In the next step we will add two lines to create a range around the regression line.

x <- 1:20
y <- c(29,33,91,88,77,110,157,185,138,189,201,205,187,177,168,201,222,278,270,285)
plot(x,y)

lo <- loess(y~x, span = 1.5)
pr <- predict(lo)
lines(pr, lwd=2)

lines(pr-20, lty=’dashed‘, col=’blue‘, lwd=1)
lines(pr+20, lty=’dashed‘, col=’blue‘, lwd=1)

R28_c

Last but not least we will fill the area between the two dashed lines. This can be done by using the polygon function and defining a transparent color. The following source code shows the full example with the smooth regression line and a transparent area around this line.

x <- 1:20
y <- c(29,33,91,88,77,110,157,185,138,189,201,205,187,177,168,201,222,278,270,285)
plot(x,y)

lo <- loess(y~x, span = 1.5)
pr <- predict(lo)
lines(pr, lwd=2)

lines(pr-20, lty=’dashed‘, col=’blue‘, lwd=1)
lines(pr+20, lty=’dashed‘, col=’blue‘, lwd=1)

polygon(c(x, rev(x)), c(pr-20, rev(pr+20)), col=’#00009920′, border=NA)

R28_d

Advertisements
Dieser Beitrag wurde unter R veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s