[R] Again, about boxplot

Marc Schwartz marc_schwartz at comcast.net
Fri Sep 12 17:41:40 CEST 2008


on 09/12/2008 10:36 AM Marc Schwartz wrote:
> on 09/12/2008 10:07 AM cathelf wrote:
>> Thank you for your guys reply for my previous question. But I got one more
>> question about the boxplot. With the code in the R-help:
>>
>> boxplot(len ~ dose, data = ToothGrowth,
>>         boxwex = 0.25, at = 1:3 - 0.2,
>>         subset = supp == "VC", col = "yellow",
>>         main = "Guinea Pigs' Tooth Growth",
>>         xlab = "Vitamin C dose mg",
>>         ylab = "tooth length", ylim = c(0, 35), yaxs = "i")
>> boxplot(len ~ dose, data = ToothGrowth, add = TRUE,
>>         boxwex = 0.25, at = 1:3 + 0.2,
>>         subset = supp == "OJ", col = "orange")
>> legend(2, 9, c("Ascorbic acid", "Orange juice"),
>>        fill = c("yellow", "orange"))
>>
>> I got 6 boxplots, which is ordered as "0.5, 0.5, 1, 1, 2, 2"
>> How can I reorder the 6 boxplots as "0.5, 1, 2,  0.5, 1, 2"?
>>
>> Thank you very much!
> 
> Here is one approach:
> 
> # Create a new DF, adding a column with the interaction of supp and
> # dose.
> DF <- cbind(ToothGrowth,
>             SD = interaction(ToothGrowth$supp, ToothGrowth$dose,
>                              lex.order = TRUE))
> 
> # Note DF$SD and the ordering of the factor levels, which is
> # the order of the boxes in boxplot()
>> DF$SD
>  [1] VC.0.5 VC.0.5 VC.0.5 VC.0.5 VC.0.5 VC.0.5 VC.0.5 VC.0.5 VC.0.5
> [10] VC.0.5 VC.1   VC.1   VC.1   VC.1   VC.1   VC.1   VC.1   VC.1
> [19] VC.1   VC.1   VC.2   VC.2   VC.2   VC.2   VC.2   VC.2   VC.2
> [28] VC.2   VC.2   VC.2   OJ.0.5 OJ.0.5 OJ.0.5 OJ.0.5 OJ.0.5 OJ.0.5
> [37] OJ.0.5 OJ.0.5 OJ.0.5 OJ.0.5 OJ.1   OJ.1   OJ.1   OJ.1   OJ.1
> [46] OJ.1   OJ.1   OJ.1   OJ.1   OJ.1   OJ.2   OJ.2   OJ.2   OJ.2
> [55] OJ.2   OJ.2   OJ.2   OJ.2   OJ.2   OJ.2
> Levels: OJ.0.5 OJ.1 OJ.2 VC.0.5 VC.1 VC.2
> 
> # Now do the boxplot
> boxplot(len ~ SD, data = DF, boxwex = 0.25, at = c(1:3, 5:7),
>         xlim = c(1, 7), col = c(rep("orange", 3), rep("yellow", 3)))

One quick tweak, simplifying the color sequence:

boxplot(len ~ SD, data = DF, boxwex = 0.25, at = c(1:3, 5:7),
        xlim = c(1, 7), col = rep(c("orange", "yellow"), each = 3))

Regards,

Marc



More information about the R-help mailing list