我需要将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个箱形图。
答案 0 :(得分:2)
此示例使用内置数据集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)
答案 1 :(得分:1)
要自定义基本绘图中的轴,您需要对其进行逐段重建:
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))