【问题标题】:Rotate x-axis labels at a given degree for boxplot in R以给定角度旋转 R 中箱线图的 x 轴标签
【发布时间】:2020-08-23 19:53:26
【问题描述】:

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

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 可以垂直旋转它们,但这并不完全是我需要的。

我怎么能这样做?谢谢。

【问题讨论】:

    标签: r boxplot


    【解决方案1】:

    首先,将boxplot() 的输出存储为对象。它包含组的名称。您可以使用$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))
    

    【讨论】:

    • 它有效,但标签在情节内部,我怎么能把它们设置在外面?
    • @ahbon 您可以通过从par("usr")[3] 中减去一个数字来将标签调整到任何位置。在我的示例中,我减去了0.3。该数字取决于您的数据范围。
    • 我使用par("usr")[3]-0.1,但似乎没有任何改变。
    • @ahbon 我的数据范围约为 4,但您的数据范围约为 40。因此,在您的情况下,减去的数字将是 5~10。 IE。 par("usr")[3] - 5 ~ par("usr")[3] - 10.
    【解决方案2】:

    一些测试数据:

    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 度。

    【讨论】:

    • emm,看起来很复杂,所以也许我应该使用las = 2
    • 一旦定义了x_axis_labels 函数,它一点也不复杂:只需调用boxplot() 获取绘图,调用x_axis_labels() 获取标签:2 行代码。跨度>
    • 函数定义可能看起来很复杂,因为它包含额外的“工作”来尝试解决垂直标签节奏的问题,使用text() 并不总是那么简单,因为它可能取决于绘图的 y 轴范围...
    猜你喜欢
    • 1970-01-01
    • 2017-07-01
    • 2018-02-22
    • 2018-01-05
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    相关资源
    最近更新 更多