0

I have a data frame like so:

df= data.frame(cond = c(rep('N', 5), rep('Y', 5)),
               var1 = rnorm(10),
               var2 = rnorm(10),
               var3= rnorm(10))

which looks like this:

    > df
   cond       var1       var2       var3
1     N -0.6115370  0.4215755  1.6492281
2     N  0.1588611 -0.9044593 -0.5339298
3     N -1.0643301  0.1991867  0.6987310
4     N -0.8418736 -1.0986175 -0.3845572
5     N  0.3425105  0.2201171  1.2721364
6     Y  0.1737336 -0.7504061 -0.0856138
7     Y  0.9686804 -0.6037347  0.1050365
8     Y  0.1226120  1.1669462 -0.6542081
9     Y -1.0073227  0.3648727  0.6253705
10    Y -0.1099620  0.6722126 -2.2743869

I'd like to accomplish a plot similar to what's shown in the answer to this question: Plot multiple variables on y-axis with the same x-axis using ggplot in r

except I'd like to plot boxplots. Ideally, I'd have multiple panes, one for each "varN" variable, and each pane would be a set of two boxplots, varN ~ condition. This is a bit similar to lattice plot y~x|var. How do I accomplish this with boxplot?

Note: I am aware that I probably need to melt row id and condition, and I tried that, but couldn't quite get it to work.

1
  • I think I need to be using facet().... Getting somewhere.... Commented Dec 12, 2017 at 4:45

1 Answer 1

1
set.seed(1)
df= data.frame(cond = c(rep('N', 5), rep('Y', 5)),
               var1 = rnorm(10),
               var2 = rnorm(10),
               var3= rnorm(10))


df
     cond       var1        var2        var3
    1     N -0.6264538  1.51178117  0.91897737
    2     N  0.1836433  0.38984324  0.78213630
    3     N -0.8356286 -0.62124058  0.07456498
    4     N  1.5952808 -2.21469989 -1.98935170
    5     N  0.3295078  1.12493092  0.61982575
    6     Y -0.8204684 -0.04493361 -0.05612874
    7     Y  0.4874291 -0.01619026 -0.15579551
    8     Y  0.7383247  0.94383621 -1.47075238
    9     Y  0.5757814  0.82122120 -0.47815006
    10    Y -0.3053884  0.59390132  0.41794156

> library(reshape)
> library(ggplot2)

cc = melt(df)
>head(cc,15)
   cond variable      value
1     N     var1 -0.6264538
2     N     var1  0.1836433
3     N     var1 -0.8356286
4     N     var1  1.5952808
5     N     var1  0.3295078
6     Y     var1 -0.8204684
7     Y     var1  0.4874291
8     Y     var1  0.7383247
9     Y     var1  0.5757814
10    Y     var1 -0.3053884
11    N     var2  1.5117812
12    N     var2  0.3898432
13    N     var2 -0.6212406
14    N     var2 -2.2146999
15    N     var2  1.1249309

ggplot(cc,aes(cond,value))+geom_boxplot()+facet_grid(~variable)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.