Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Draw All Axis Labels (Prevent Some From Being Skipped)

Tags:

When I manually add the following labels with (axis(1, at=1:27, labels=labs[0:27])):

> labs[0:27]
 [1] "0\n9.3%"  "1\n7.6%"  "2\n5.6%"  "3\n5.1%"  "4\n5.7%"  "5\n6.5%"  "6\n7.3%"  "7\n7.6%"  "8\n7.5%"  "9\n7%"    "10\n6.2%" "11\n5.2%"
[13] "12\n4.2%" ........

I get the following:

enter image description here

How do I force all labels to be drawn so 1,3,5,6, and 11 are not skipped? (also, for extra credit, how do I shift the whole thing down a few pixels?)

like image 641
Kyle Brandt Avatar asked Dec 31 '11 15:12

Kyle Brandt


People also ask

How do I show all axis labels in R?

There are basically two major tricks, when we want to show all axis labels: We can change the angle of our axis labels using the las argument. We can decrease the font size of the axis labels using the cex. names argument.

How do I suppress axis in R?

The option axes=FALSE suppresses both x and y axes. xaxt="n" and yaxt="n" suppress the x and y axis respectively.

How do I turn off axis ticks in R?

Set xaxt = "n" and yaxt = "n" to remove the tick labels of the plot and add the new labels with the axis function. Note that the at argument sets where to show the tick marks.

How do I change the Y axis increments 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.


1 Answers

If you want to force all labels to display, even when they are very close or overlapping, you can "trick" R into displaying them by adding odd and even axis labels with separate calls to the axis function, as follows:

labs <-c("0\n9.3%","1\n7.6%","2\n5.6%","3\n5.1%","4\n5.7%","5\n6.5%","6\n7.3%",
         "7\n7.6%","8\n7.5%","9\n7%", "10\n6.2%","11\n5.2%","12\n4.2%",13:27)
n=length(labs)
plot(1:28, xaxt = "n")
axis(side=1, at=seq(1,n,2), labels=labs[seq(1,n,2)], cex.axis=0.6)
axis(side=1, at=seq(2,n,2), labels=labs[seq(2,n,2)], cex.axis=0.6)

enter image description here

You can play with cex.axis to get the text size that you want. Note, also, that you may have to adjust the number of values in at= and/or labels= so that they are equal.

I agree with @PLapointe and @joran that it's generally better not to tamper with R's default behavior regarding overlap. However, I've had a few cases where axis labels looked fine even when they weren't quite a full "m-width" apart, and I hit on the trick of alternating odd and even labels as a way to get the behavior I wanted.

like image 178
eipi10 Avatar answered Sep 24 '22 07:09

eipi10