问题
I want to plot Delta~Project.Types in R. I have 10 Project Types. I know how to do the boxplot : boxplot(Delta~Project.Types). However, how can I put the fivenum (min, max, 1st, 2nd, and 3rd quantile) on each boxplot? How can I do for that every boxplot of the image will have its five number shown? That would be easier to compare the boxplots when the values are shown
Thanks!
回答1:
The stats you want can also be obtained with fivenum
five <- by(InsectSprays$count, InsectSprays$spray, fivenum)
do.call(cbind, five)
# A B C D E F
# [1,] 7.0 7.0 0.0 2.0 1.0 9
# [2,] 11.0 12.0 1.0 3.5 2.5 12
# [3,] 14.0 16.5 1.5 5.0 3.0 15
# [4,] 18.5 18.0 3.0 5.0 5.0 23
# [5,] 23.0 21.0 7.0 12.0 6.0 26
Alternatively, these stats are one of the return values of boxplot
(note that you need to use range = 0
to get the min and max since there are some values which are outlying):
bp <- boxplot(count ~ spray, data = InsectSprays, col = "lightgray", range = 0)
bp$stats
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 7.0 7.0 0.0 2.0 1.0 9
# [2,] 11.0 12.0 1.0 3.5 2.5 12
# [3,] 14.0 16.5 1.5 5.0 3.0 15
# [4,] 18.5 18.0 3.0 5.0 5.0 23
# [5,] 23.0 21.0 7.0 12.0 6.0 26
Then just add to each box:
text(x = col(bp$stats) - .5, y = bp$stats, labels = bp$stats)
回答2:
You can add a "legend" to a base R plot that contains what you want like this:
legend("topright", bty = "n", legend = summary(Delta))
I'm assuming that it's "Delta" that you're running summary() on, so change that as needed. You can modify the appearance of what shows up in the legend using paste(), i.e.
legend("topright", bty = "n", legend = c(paste("min =", summary(Delta)[1]),
paste("max =", summary(Delta)[2])))
etc.
来源:https://stackoverflow.com/questions/26692248/how-to-put-values-on-boxplot-in-r-for-several-boxplot-in-one-image