Adding a table of statistics to a boxplot in R

2020-04-14 02:52发布

问题:

I have created two boxplots on the same graph, as per code below

a = c(1,1,1,2,2,2,2,2,5,5,5,5,5,6,5,4,7)

b = c(1,1,2,2,2,2,2,2,5,5,5,5,5,6,5,3,8)

boxplot(  a
        , b
        , names = c("Category a", "Category b")
        , staplewex = 1 
        , horizontal = TRUE ) 

I would like to also add the important data points, Q1 median etc, as labels or as a summary table on the graph similar to a legend - is this possible?

Thanks

回答1:

Thanks for your help the plotrix package works!

install.packages("plotrix")

library(plotrix)

table <- sapply(as.data.frame(cbind(a,b)),summary)

addtable2plot(22,2,table)


回答2:

I offer this code as another approach using gridExtra:

library(gridExtra)
set.seed(1)
mydata <- data.frame(a=1:50, b=rnorm(50))
mytable <- cbind(sites=c("site 1","site 2","site 3","site 4"), mydata[10:13,])
k <- ggplot(mydata,aes(x=a,y=b)) + geom_point(colour="blue") + 
  geom_point(data=mydata[10:13, ], aes(x=a, y=b), colour="red", size=5) + 
  annotation_custom(tableGrob(mytable), xmin=35, xmax=50, ymin=-2.5, ymax=-1)


标签: r boxplot