## Data visualization in R: Two different x-axes

It is possible to create two different axes for x values. So you may show two different data sets within one plot. In this article we want to implement an example plot to show a weather forecast which contains the likelihood of rain and the expected rainfall. The example shows how to create two x-axes. But you may use the same concept to create two y-axes.

At first we have to create some data vectors for the days, the likelihood and the quantity of rain.

day <- c(‚M‘,’T‘,’W‘,’T‘,’F‘,’S‘,’S‘)
dayCounter <- c(1,2,3,4,5,6,7)
likelihood <- c(0,10,40,68,80,23,5)
quantitiy <- c(0,0.2,0.4,2.3,2.1,1.1,0.1)

At next we will create the data plot and show the first data set, the likelihood of rain. Furthermore we have to define a margin different to the default one because we need more space on the right side for the second x-axis.

par(mar=c(5, 4, 4, 5))
plot(dayCounter, likelihood, type=’l‘, xlab=’Day‘, ylab=’Likelihood %‘, xaxt=’n‘, ylim=c(0,100))
axis(1, at=dayCounter, labels=day)

The following graphic shows the resulting plot. At next we will create the second plot. As we want to show the second data set inside the existing plot it is necessary to execute the par function first. By passing the according parameter we prevent R from clearing the graphics device.

par(new=TRUE)
plot(dayCounter, quantitiy, type=’S‘, axes=FALSE, bty=’n‘, xlab=“, ylab=“, ylim=c(0,10))

The second plot should use the definitions from the first one. So we have to disable plotting of new axes with axes=FALSE and hide new axes titles with xlab=“, ylab=“. Furthermore we will suppress the box around the plot with bty=’n‘.

Now we are able to add our second x-axis and an according title. The title will be created by using the mtext command. The parameter side=4 draws the text on the right side and the parameter line=3 specifies the according margin line to place the text.

axis(4, at=c(0,2,4,6,8,10))
mtext(‚Quantity (l/m2)‘, side=4, line=3)

The following source code shows the complete example

day <- c(‚M‘,’T‘,’W‘,’T‘,’F‘,’S‘,’S‘)
dayCounter <- c(1,2,3,4,5,6,7)
likelihood <- c(0,10,40,68,80,23,5)
quantitiy <- c(0,0.2,0.4,2.3,2.1,1.1,0.1)

par(mar=c(5, 4, 4, 5))
plot(dayCounter, likelihood, type=’l‘, xlab=’Day‘, ylab=’Likelihood %‘, xaxt=’n‘, ylim=c(0,100))
axis(1, at=dayCounter, labels=day)

par(new=TRUE)
plot(dayCounter, quantitiy, type=’S‘, axes=FALSE, bty=’n‘, xlab=“, ylab=“, ylim=c(0,10))
axis(4, at=c(0,2,4,6,8,10))
mtext(‚Quantity (l/m2)‘, side=4, line=3)

This will create the following plot. Dieser Beitrag wurde unter R veröffentlicht. Setze ein Lesezeichen auf den Permalink.