Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: multiple x axis with annotations

Tags:

plot

r

Is it possible to add more than one x-axis to a plot in R? And to put an annotation next to each scale?

Edit > here's the result of Nick Sabbe idea. For the annotation (a little text at the left of each axis), is it possible ?

enter image description here

like image 559
Nicolas Rosewick Avatar asked Dec 09 '11 09:12

Nicolas Rosewick


People also ask

Can you have two X axis in R?

Finally, we use the annotate function twice to add two x-axis rows to our plot. Note that the vertical adjustment of the second call of the annotate function is higher than in the first call. In Figure 4 you can see that we have plotted a ggplot2 line plot with two x-axis labels with the previous code.

How do you specify the x axis in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

What does XLAB mean in R?

xlab="x-axis label", ylab="y-axis label") Many other graphical parameters (such as text size, font, rotation, and color) can also be specified in the title( ) function.

How do you add X axis labels in R?

To set labels for X and Y axes in R plot, call plot() function and along with the data to be plot, pass required string values for the X and Y axes labels to the “xlab” and “ylab” parameters respectively. By default X-axis label is set to “x”, and Y-axis label is set to “y”.


2 Answers

You can use the line argument of axis() to place an axis higher or lower, this way you can make multiple axes. With mtext() you can then add a label to the side. Do note that the plot itself is only on one scale so you need to rescale the points and labels of the other scale accordingly:

# Plot and first axis:
plot(1:10,1:10,bty="n",col="red",pch=16,axes=FALSE,xlab="",ylab="")
axis(2,0:11,las=1)
axis(1,0:11,line=1,col="red",col.ticks="red",col.axis="red")
mtext("Label 1",1,line=1,at=0.2,col="red")

# Secondary points and axis:
points(rnorm(10,50,20)/10, rnorm(10,5,2),pch=16, col="blue" )
axis(1,0:11,labels=0:11*10,line=3,col="blue",col.ticks="blue",col.axis="blue")
mtext("Label 2",1,line=3,at=0.2,col="blue")

enter image description here

like image 196
Sacha Epskamp Avatar answered Oct 13 '22 22:10

Sacha Epskamp


You can use ?axis for that. Parameter at is in the scale of the original axis of the plot, and you can pass labels to show other values.

You have to scale the axess labels yourself, though.

A very simple/silly example:

plot(1:10,1:10)
axis(side=4, at=c(3,7), labels=c(30,70))

Finally, note that most people consider adding multiple axes to a plot bad form...

like image 39
Nick Sabbe Avatar answered Oct 13 '22 22:10

Nick Sabbe