ggplot2:添加背景图层

时间:2010-08-12 16:42:55

标签: r ggplot2

我想在我的堆积区域图集的背景中添加暗/亮相位信息,以突出显示光线如何影响曲线的形状。我的数据框看起来像这样:

> str(MDist.median)
'data.frame':   2880 obs. of  6 variables:
 $ groupname: Factor w/ 8 levels "rowA","rowB",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ fCycle   : Factor w/ 6 levels "predark","Cycle 1",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ fPhase   : Factor w/ 2 levels "Light","Dark": 2 2 2 2 2 2 2 2 2 2 ...
 $ starttime: num  0.3 60 120 180 240 300 360 420 480 540 ...
 $ dists    : Factor w/ 3 levels "inadist","smldist",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value    : num  110 123 124 128 132 ...

示例数据:

> head(MDist.median)
  groupname  fCycle fPhase starttime   dists  value
1      rowA predark   Dark       0.3 inadist 110.00
2      rowA predark   Dark      60.0 inadist 123.25
3      rowA predark   Dark     120.0 inadist 124.10
4      rowA predark   Dark     180.0 inadist 128.35
5      rowA predark   Dark     240.0 inadist 131.80
6      rowA predark   Dark     300.0 inadist 140.30

我的区域图通过x轴上的起始时间在y轴上堆叠3种dists

dists.med.areaplot <- qplot(starttime,value,fill=dists,facets=~groupname,
 geom='area',data=MDist.median, stat='identity') + 
 labs(y='median distances', x='time(s)', fill='Distance Types')+
 opts(title='Changes in Fish Activity and Activity Type') + 
 scale_fill_brewer(type='seq')

我想在每个绘图后面添加垂直矩形,这些矩形通过每个fCycle的最小和最大开始时间水平定位,其中fPhase ==“Dark”。我在GIMP中编辑了我的图形集以显示我的意思:

my altered graphset

我一直在尝试使用主题但是效果不佳。想法?

ETA

所以,使用这个例子(来自Hadley的website):

(unemp <- qplot(date, unemploy, data=economics, geom="line", 
  xlab = "", ylab = "No. unemployed (1000s)"))

presidential <- presidential[-(1:3), ]

yr <- range(economics$unemploy)
unemp + geom_rect(
  aes(NULL, NULL, xmin = start, xmax = end, fill = party), 
  ymin = yr[1], ymax = yr[2], data = presidential) + 
  scale_fill_manual(values = alpha(c("blue", "red"), 0.2)
)

我可以用我的数据做到这一点:

dists.med.areaplot + geom_rect(
      aes(NULL, NULL, xmin = phase_start, xmax = phase_end, fill = fPhase), 
      ymin = -Inf, ymax = Inf, data = phase_starts) + 
      scale_fill_manual(values = alpha(c("#cccccc", "#000000"), 0.2)
    )

将Light和Dark类别添加到图例中,并将所有颜色更改为灰色。

如果我遗漏了scale_fill_manual(values = alpha(c("#cccccc", "#000000"), 0.2),我会得到我期望的图例更改的矩形,但它们完全不透明,在我的原始图形之上,并使用我的颜色序列中的前2种颜色。

如何在原始图块后面制作geom_rect?

1 个答案:

答案 0 :(得分:8)

使用更新后的代码,我会仅考虑dark个区域的子集。然后添加

geom_rect(data = dark.subset, aes(xmin = phase_start, xmax = phase_end), 
              ymin = -Inf,
              ymax = Inf,
              fill = alpha("#000000", 0.2))

这样可以避免将lightdark映射到任何比例。至于出现在顶部,以不同的顺序添加您的geoms:

ggplot(...)+
  geom_rect(...)+
  geom_area(...)