[英]Rotate x-axis labels at a given degree for boxplot in R
首先,将 boxplot boxplot()
的 output 存储为 object。 它包含组的名称。 您可以使用$names
来获取它们。 然后使用text()
添加轴的标签。 参数srt
适用于text()
。
tmp <- boxplot(y ~ x, data = df, col = c("gold","darkgreen"), xaxt = "n")
tick <- seq_along(tmp$names)
axis(1, at = tick, labels = F)
text(tick, par("usr")[3] - 0.3, tmp$names, srt = 45, xpd = T)
数据
df <- data.frame(x = sample(100:110, 100, T), y = rnorm(100))
一些测试数据:
mydata=lapply(1:5,function(i) rnorm(100,mean=i))
names(mydata)=c("first","second","third","fourth","fifth")
首先,plot 没有 x 轴的箱线图:
boxplot(mydata,xaxt="n",xlab="")
然后,我们制作一个 function 来添加文本 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()
最后,我们将新的 function 称为 plot 轴刻度标签:
x_axis_labels(labels=names(mydata),every_nth=1,adj=1,srt=45)
这里我们利用 function 中的...来传递旋转/对齐参数:adj=1 表示将文本标签右对齐,srt=45 表示将它们旋转 45 度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.