Search code examples
rboxplot

Boxplot for multiple variables


I am looking for how to make a box plot with the base function boxplot() in R for two animal groups and two sex groups. I need four boxes for female sheep, male sheep, female goats, and male goats to show the difference in animal height.

  animal    sex height
1   sheep female    117
2   sheep female    115
3   sheep female    110
4   sheep   male     95
5   sheep   male    121
6   sheep   male    106
7   sheep female     98
8   sheep female    119
9   sheep female    100
10  sheep   male    121
11   goat   male    130
12   goat   male    125
13   goat   male    134
14   goat female    112
15   goat female    122
16   goat female    129
17   goat   male    135
18   goat   male    139

With this code I have only two boxes for sheep and goats:

boxplot (height ~ animal)

Solution

  • I haven't tried it on your data, but the last example in ?boxplot shows the use of an interaction: something like

    boxplot (height ~ animal:sex, data = your_data)
    

    should do it (see the examples for more details on specifying fill colours and other decorations).

    (@GregorThomas suggests + instead of :, and the help for the "formula" argument says

    Note that ‘~ g1 + g2’ is equivalent to ‘g1:g2’.

    )