Data visualization in R: Legend

If you show different data sets in one plot it becomes necessary to label these data sets. This is normally done by adding a legend. So let’s have a look at an example. The following code creates a plot to show the cosine, sine and tangent function.

x <- seq(0,7,0.1)
y1 <- cos(x)
y2 <- sin(x)
y3 <- tan(x)
 
plot(0, 0, type=’n‘, xlab=’x‘, ylab=’y‘, xlim=c(0,7), ylim=c(-2,3), bty=’n‘, xaxt=’n‘, yaxt=’n‘)
axis(1, pos=0)
axis(2, pos=0)
 
lines(x, y1, col=’red‘, lwd=2)
lines(x, y2, col=’blue‘, lwd=2)
lines(x, y3, col=’green‘, lwd=2)
 
legend(‚topright‘, title=’Legend‘, c(‚cosine‘,’sine‘,’tangent‘), col=c(‚red‘,’blue‘,’green‘), bg=’grey95′, lty=1, lwd=2, cex=0.75)

 
This will create the following plot.

R15_a
 
Now let’s have a look at the parameters we used to define the plot appearance.
The following parameters where set in the plot function.

  • type=’n‘: hides the plot content (because we want add the different data sets later on)
  • xlab=’x’/ylab=’y‘: titles of the axes
  • xlim=c(0,7)/ylim=c(-2,3): upper and lower limits of the axes
  • bty=’n‘: removes the plot box
  • xaxt=’n’/yaxt=’n‘: hides the axes (because we want to create them on defined positions)

 
Then we have created the two axes on defined positions. This is necessary because the standard axes will be shown on the bottom and the left side of the plot area. So the x-axis would be shown. Afterwards the data is shown with the lines function. The parameter lwd defines the line width.

At last the legend is shown. The following parameters where set.

  • ‚topright‘: position of the legend
  • title=’Legend‘: title of the legend
  • c(‚cosine‘,’sine‘,’tangent‘): content of the legend
  • col=c(‚red‘,’blue‘,’green‘): colors of the text marks
  • bg=’grey95′: background color
  • lty=1/lwd=2: line type and line width for the text marks
  • cex=0.75: scale of the legend (scale it to 75% of the standard size)

 

Werbung
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 )

Facebook-Foto

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

Verbinde mit %s