Add an approximate x-axis number of num for each window to boxplot in ggplot2

I can do this with the classic boxplot

. We're using inline data here: PlantGrown

as an example.

attach(PlantGrowth)    
boxplot(weight~group,data=PlantGrowth,xaxt="n")
PlantGrowthSum=ddply(PlantGrowth,.(group),summarise,sum=length(weight))

> PlantGrowthSum
   group sum
1  ctrl  10
2  trt1  10
3  trt2  10

axis(1,1:3,paste(PlantGrowthSum$group,"(",PlantGrowthSum$sum,")",sep=""))

      

Boxplot with sum number for each box

Here's the question, how about ggplot2

?

library(ggplot2)
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group))
    + geom_boxplot()
    +theme(axis.text.x=element_blank())
    +theme(axis.text.x=1:3)
bp

      

But it failed. Any hints on which parameter to tweak?

+3


source to share


1 answer


Since the x values ​​are discrete in this case, you must use scale_x_discrete()

to label the x axis.

bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group))+
geom_boxplot()
bp+scale_x_discrete(labels=paste(PlantGrowthSum$group,"(",PlantGrowthSum$sum,")",sep=""))

      



enter image description here

More information and an example on scales and other ggplot2 plot elements can be found in the ggplot2 documentation site .

+5


source







All Articles