箱线图的倾斜 x 轴标签

Slanted x-axis labels for boxplots

我需要将 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 个箱线图。

此示例使用内置数据集 mtcars。关键是不要绘制 x-axis 标签,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)

要在基本绘图中自定义坐标轴,您需要重建它们piece-by-piece:

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))