繁体   English   中英

在 R 中以给定角度旋转 x 轴标签以获取箱线图

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

我用下面的代码生成一个箱线图:

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

但是您可能会注意到 x 轴上的一些标签丢失了,所以我想将它们旋转 45 度。 我添加了srt=45 ,但它不起作用。

通过设置las=2可以垂直旋转它们,但这并不完全是我需要的。

我怎么能那样做? 谢谢。

在此处输入图像描述

首先,将 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM