0

For university, I am tasked to create two whisker-boxplots side-by-side in the same plot. (And then make critical comments and observations about them)

The sway data frame this exercise is based on, can be obtained by the following R commands:

sway <-
  structure(list(Age = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L),
                                 .Label = c("Elderly", "Young"), class = "factor"),
                 FBSway = c(19L, 30L, 20L, 19L, 29L, 25L, 21L, 24L, 50L, 25L, 21L, 17L, 15L, 14L, 14L, 22L, 17L), 
                 SideSway = c(14L, 41L, 18L, 11L, 16L, 24L, 18L, 21L, 37L, 17L, 10L, 16L, 22L, 12L, 14L, 12L, 18L)),
            .Names = c("Age", "FBSway", "SideSway"),
            class = "data.frame", row.names = c(NA, -17L))

The idea is that we create a boxplot of sway$FBsway for both the Young as the Elderly age groups, in the same plot.

I know about the par(mfrows=c(1,2)) function, but this creates two loose plots, side-by-side.

How do I transform the sway data frame into a format that boxplot() can use to create the desired boxplots in a single plot?

rawr
  • 20,481
  • 4
  • 44
  • 78
Qqwy
  • 5,214
  • 5
  • 42
  • 83

2 Answers2

1

Does this do what you want?

plot(as.numeric(sway$FBSway) ~as.factor(sway$Age))
R.S.
  • 2,093
  • 14
  • 29
  • Wow! That does exactly what I want! Could you elaborate on why the `as.numeric` and `as.factor` casts are necessary here, for this to work? – Qqwy Sep 21 '16 at 16:56
  • Or was the problem here that I blindly stared at `boxplot()` whereas `plot()` 'just makes' a boxplot for you, given the correct input? – Qqwy Sep 21 '16 at 16:59
  • 1
    Actually they might not be so necessary. I just did so to keep things unambiguous . And to further remove any ambiguity, you can substitute `plot` with `boxplot` – R.S. Sep 21 '16 at 17:00
  • It's the formula sign, ~ that made it the generic plot function call boxplot. It calls plot.formula And here's quoting from the documentation for plot.formula : `If y is an object (i.e., has a class attribute) then plot.formula looks for a plot method for that class first. Otherwise, the class of x will determine the type of the plot. For factors this will be a parallel boxplot, and argument horizontal = TRUE can be specified` – R.S. Sep 21 '16 at 17:06
  • I see! I tried the `~`-syntax before, but having `sway$Age` as the first operand. This threw an error. – Qqwy Sep 22 '16 at 11:14
  • I use the mnemonic 'y axis depends on x axis' to remember `y~x` – R.S. Sep 22 '16 at 12:20
0

How about this?

library(ggplot2)
library(reshape2)
sway <- melt(sway)

ggplot(sway, aes(variable, value)) + geom_boxplot() + facet_wrap(~Age)

enter image description here

ggplot(sway, aes(Age, value)) + geom_boxplot() + facet_wrap(~variable)

enter image description here

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63