I need the x-axis labels to be slanted at 45 degrees. Also, how do I reduce the number of boxplots shown in each visual without changing the source data?
I know the code I need to add is srt = 45
but where? Also, how do I change code below so that each visual only shows 3 boxplots?
boxplot(Transport$mph ~ Transport$CarType, main = "Mph by Car Type",
xlab = "Car Type", ylab= "Mph", col= "grey")
Currently, the x-axis labels are horizontal so not all the labels are showing. I want them to be slanted at 45 degrees so that all the labels can be seen. Also, I want to know how to specify smaller quantity of boxplots in each visual as there are too many boxplots in one visual currently. I am happy to have many visuals showing only 3 boxplots each.
This example uses built in data set mtcars
. The key is to not plot the x-axis labels, xaxt = "n"
and then plot the labels with 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)
To customize axes in base plotting, you need to reconstruct them 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
This is somewhat easier in ggplot, since it handles a lot of the alignment, keeping track of labels, etc. for you:
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.