r boxplot tilted labels x axis

谁都会走 提交于 2019-11-30 20:07:24

An alternative following your original text expression:

par(mar=c(6, 4.1, 4.1, 2.1))

labels <- paste(c("RB-GL830-[16]-10", 
                  "RB-GL830-[16]-30",
                  "SB-GL834-[11]-10",
                  "SB-GL834-[11]-30",
                  "RB-GL843-[17]-10",
                  "RB-GL843-[17]-30"))

boxplot(count ~ spray, data = InsectSprays,
        col = "lightgray", xaxt = "n",  xlab = "")

# x axis with ticks but without labels
axis(1, labels = FALSE)

# Plot x labs at default x position
text(x =  seq_along(labels), y = par("usr")[3] - 1, srt = 45, adj = 1,
     labels = labels, xpd = TRUE)

Why use x = seq_along(labels) for label positions? The x in text is a vector of coordinates where to put the labels. If you look at ?boxplot, you find that the at argument is a "numeric vector giving the locations where the boxplots should be drawn [...]; defaults to 1:n where n is the number of boxes." Because we haven't specified the at argument in the boxplot call, the default "1:n positions" will be used. The number of boxes is of course the number of levels of your explanatory variable, which @Josh O'Brien used in his answer. To show you an alternative, I used your customized label vector instead (which of course must have the same length as the number of factor levels). seq_along generates a regular sequence from 1 to length of the argument, which corresponds to the "defaults to 1:n" at positions.

A side-note: your data seem to be in a 'wide' format. In many instances in R, it is more convenient to have the data in a 'long' format. In the plot function, you then only need to specify your x variable (e.g. location) and y variable (e.g. soil temp), instead of specifying data for every single level of x.

Look at the staxlab function in the plotrix package, it makes this (and an alternative) fairly straight forward.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!