Rotate x-axis labels at a given degree for boxplot in R

Viewed 3904

I generate a boxplot with code below:

boxplot(top10threads$affect ~ top10threads$ThreadID[], data = top10threads, xlab = "10 biggest Threads", ylab = "Affect", col=(c("gold","darkgreen")), srt=45)

But as you may notice that some labels in x-axis are missing, so I want to rotate them into 45 degrees. I added srt=45, but it doesn't work.

By setting las=2 can rotate them vertically, but it's not exactly I need.

How could I do that? Thanks.

enter image description here

2 Answers

First, store the output of boxplot() as a object. It contains names of the groups. You can use $names to get them. Then use text() to add labels on the axis. The argument srt works on text().

bp <- boxplot(y ~ x, data = df, col = c("gold", "darkgreen"), xaxt = "n")
tick <- seq_along(bp$names)
axis(1, at = tick, labels = FALSE)
text(tick, par("usr")[3] - 0.3, bp$names, srt = 45, xpd = TRUE)

Data

df <- data.frame(x = sample(100:110, 100, TRUE), y = rnorm(100))

Some test data:

mydata=lapply(1:5,function(i) rnorm(100,mean=i))
names(mydata)=c("first","second","third","fourth","fifth")

First, plot the boxplot with no x-axis:

boxplot(mydata,xaxt="n",xlab="")

Then, we make a function to add textual x-axis labels:

x_axis_labels=function(labels,every_nth=1,...) {
    axis(side=1,at=seq_along(labels),labels=F)
    text(x=(seq_along(labels))[seq_len(every_nth)==1],
        y=par("usr")[3]-0.075*(par("usr")[4]-par("usr")[3]),
        labels=labels[seq_len(every_nth)==1],xpd=TRUE,...)
}
# axis() draws the axis with ticks at positions specified by at.  Again, we don't plot the labels yet.
# text() plots the labels at positions given by x and y.
# We estimate the y-positions from the values of the y-axis (using par("usr")),
# and specify xpd=TRUE to indicate that we don't want to crop plotting to within the plot area
# Note that we select the [seq_len(every_nth)==1] elements of both the x positions and the labels, 
# so we can easily skip labels if there would be too many to cram in otherwise.  
# Finally, we leave a ... in the function so we can pass additional arguments to text()

Finally, we call the new function to plot the axis tick labels:

x_axis_labels(labels=names(mydata),every_nth=1,adj=1,srt=45)

Here we take advantage of the ... in the function to pass the rotation/justification parameters: adj=1 specifies to right-justify the text labels, and srt=45 indicates to rotate them by 45 degrees.

Related