簡體   English   中英

箱形圖的傾斜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軸標簽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)

要自定義基本繪圖中的軸,您需要對其進行逐段重建:

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

帶旋轉標簽的ggplot

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM