一些测试数据:
mydata=lapply(1:5,function(i) rnorm(100,mean=i))
names(mydata)=c("first","second","third","fourth","fifth")
首先,绘制没有 x 轴的箱线图:
boxplot(mydata,xaxt="n",xlab="")
然后,我们创建一个函数来添加文本 x 轴标签:
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()
最后,我们调用新函数来绘制轴刻度标签:
x_axis_labels(labels=names(mydata),every_nth=1,adj=1,srt=45)
这里我们利用函数中的 ... 来传递旋转/对齐参数:adj=1 表示将文本标签右对齐,srt=45 表示将它们旋转 45 度。