使用ggplot2,qplot或其他绘制多个y变量的箱线图

时间:2015-02-10 07:13:05

标签: r function variables ggplot2

我正在寻找用x = season和function = event绘制许多y变量的箱线图的方法。我想把所有的情节画在一起,如:

拳头情节:x =季节,y = var1 by function = event 第二个图:x = season,y = var1,by fuction = event ..

我的数据如下所示。实际上,我有很多变数。

............................................... ..........................

    event     season      var1      var2     var3
1  event_free wet.summer 14.193489 16.786347 22.65968
2  event_free       fall  3.209114  9.948187 15.44799
3       event       fall  4.564315 10.647883 34.24658
4       event       fall 20.152646 31.114422 33.04899
5  event_free       fall  3.944427  6.431695 10.27153
6  event_free       fall  9.994351 16.110569 22.73702
7  event_free       fall  3.100501  6.507310 14.37157
8  event_free     winter  2.631117        NA 13.88889
9       event     winter 20.745972 22.629357 29.27042
10      event     winter 15.929737 21.355657 36.45409
11 event_free     winter  7.383920  7.418910 11.85094
12      event     winter 17.011810 20.320714 44.18071
13      event     spring 12.501078 14.260404 39.08531
14      event     spring 26.224773 32.536549 46.90560

............................................... ..........................

我发现很多方法可以使用ggplot2或qplot来绘制一个y变量和一个函数(例如:event,here),但是找不到如何为多个y变量绘制多个绘图。
非常感谢你的帮助!!

纤细

1 个答案:

答案 0 :(得分:2)

以下是ggplot2

的方法
library(reshape2)
library(ggplot2)

# Assume your data frame is named dat
dat.m = melt(dat, id.var=c("event","season"))
dat.m$season = factor(dat.m$season, levels=c("winter", "spring","wet.summer","fall"))

# If you want the two levels of event plotted side by side
ggplot(dat.m, aes(season, value, colour=event)) +
  facet_grid(. ~ variable) +
  geom_boxplot(width=0.7)

enter image description here

# If you want the levels of event to be faceted (plotted in separate panels)
ggplot(dat.m, aes(season, value)) +
  facet_grid(event ~ variable) +
  geom_boxplot()

enter image description here