【问题标题】:Slanted x-axis labels for boxplots箱线图的倾斜 x 轴标签
【发布时间】:2019-07-04 18:36:47
【问题描述】:

我需要将 x 轴标签倾斜 45 度。另外,如何在不更改源数据的情况下减少每个视觉对象中显示的箱线图数量?

我知道我需要添加的代码是srt = 45,但是在哪里?另外,如何更改下面的代码,以便每个视觉对象仅显示 3 个箱线图?

boxplot(Transport$mph ~ Transport$CarType, main = "Mph by Car Type",
    xlab = "Car Type", ylab= "Mph", col= "grey")

目前,x 轴标签是水平的,因此并非所有标签都显示出来。我希望它们倾斜 45 度,以便可以看到所有标签。另外,我想知道如何在每个视觉对象中指定较少数量的箱线图,因为目前一个视觉对象中有太多箱线图。我很高兴有许多视觉效果,每个只显示 3 个箱线图。

【问题讨论】:

  • 来自help("par") : srt 字符串旋转度数。请参阅有关crt 的评论。仅 text 支持。 只有函数 text 可以旋转非 90 倍数的角度

标签: r plot boxplot


【解决方案1】:

本示例使用内置数据集mtcars。关键是不要绘制 x 轴标签,xaxt = "n",然后用 text 绘制标签。

labs <- seq_along(unique(mtcars$cyl))

boxplot(mpg ~ cyl, data = mtcars, xaxt = "n",
    main = "Mph by Car Type",
    xlab = "Car Type", ylab= "Mph", col= "grey")
text(seq_along(unique(mtcars$cyl)), par("usr")[3], 
    labels = labs, srt = 45, adj = c(1.1, 1.1), xpd = TRUE)

【讨论】:

    【解决方案2】:

    要在基础绘图中自定义轴,您需要逐个重建它们:

    data('mpg', package = 'ggplot2')
    
    x_labs <- levels(factor(mpg$class))
    boxplot(hwy ~ class, mpg, main = "Highway MPG by car type", 
            xlab = NULL, ylab = "Highway MPG", col = "grey", xaxt = 'n')    # don't plot axis
    axis(1, labels = FALSE)    # add tick marks
    text(x = seq_along(x_labs), y = 9, labels = x_labs, 
         srt = 45,    # rotate
         adj = 1,    # justify
         xpd = TRUE)    # plot in margin
    mtext("Car Type", side = 1, padj = 6)    # add axis label
    

    这在 ggplot 中稍微容易一些,因为它会为您处理大量对齐、跟踪标签等:

    library(ggplot2)
    
    ggplot(mpg, aes(class, hwy)) + 
        geom_boxplot(fill = 'grey') + 
        labs(title = "Highway MPG by car type", x = "Car type", y = "Highway MPG") +
        theme(axis.text.x = element_text(angle = 45, hjust = 1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2013-10-23
      相关资源
      最近更新 更多