1
votes

I have a couple of box and whisker plots in R. In both, the x-axis corresponds to one categorical variable whilst the grouping colours correspond to the other.

If I draw both plots with an untransformed y-axis, they are both fine. However, if I try to square-root transform the y-axis (using: coord_trans(y = "sqrt")), one of those graph is still fine whilst the other drops the lines corresponding to the median in most boxes (except those for which there are only two groups and where the boxes are therefore slightly wider, see "Numbers" 1 and 2 on the first plot). Further, for the graph that does not draw properly, if I reduce the number of categories on my x-axis (hence getting the boxes wider again), the median lines appear again.

Is this a bug with coord_trans (if so, how can I get around it) or a problem with my code?

Thank you very much for any suggestion.

library(car)
library(gplots)
library(plyr)
library(ggplot2)
library(gridExtra)
library(gdata)

Category=factor(c(rep(1, times =3240), rep(2, times =2160)), 
                labels=c("A","B"), levels=c(1,2))
ID=factor(rep(seq(from = 1, to = 45),each = 120))
Months=factor(rep(seq(from = 1, to = 3), each = 40, times = 45),
              labels=c("Jan","Feb","Mar"),levels=c(1:3))
Obs=rnorm(5400, mean=25, sd=15)
Data=data.frame(Category,ID,Months,Obs)

Data=subset(Data, (Data$Category=="B") | !(Data$ID%in%c(1,2)) | 
              (Data$Months%in%c("Jan","Feb")))

for (j in 1:2)
{
  sel=which(Data$Category==unique(levels(Data$Category))[j])
  Observ=Data$Obs[sel]
  Month=Data$Months[sel]
  Number=droplevels(Data$ID[sel])
  Number=droplevels(Number)
  Data_used=data.frame(Number,Month,Observ)
  plot1 = ggplot(Data_used, aes(Number, Observ)) +
    geom_boxplot(aes(fill=Month, drop=FALSE), na.rm=TRUE) +  
    scale_y_continuous(breaks = c(0,20,40,60,80,100), limits=c(0,115)) + 
    coord_trans(y = "sqrt")
  plot(plot1)
}
1
very hard to help you without data or at least a picture where you show the problem. - agstudy
Replace scale_y_continuous() with scale_y_sqrt() and lose the coord_trans() line. That seems to work for me (R-2.15.3, Win7 64-bit, ggplot2-0.9.3.1). - Dennis
Thank you for the suggestion. However, I had tried this and it does not really do what I am after. As far as I understand it, scale_y_sqrt() transform all the data before plotting them (so that the median and quartiles are those on the transformed scale). What I am after is for the quartiles to be calculated on the original scale but plotted on the square root scale, which is what I think coord_trans() is meant to be doing. - user2162057

1 Answers

0
votes

@Dennis is correct in his comment that scale_y_sqrt() will correct this. Because median and quartiles are order statistics it doesn't matter whether the data are transformed before or after calculating them.