2012-05-12 39 views
11

ここで間違っていますか? 透明な灰色の24時間毎日の長方形を代わりに陰影付けしようとしています。しかし、for-loopの最後の矩形だけが描画されます(?!?)forループの代わりに手作業で行うとうまくいきます。ggplot2:プロット上で代替日を透明にする方法

これをベクトル化してforループを回避する方法はありますか? (それはqplotでできますか?) 私はggplot2を初めて使っています。はい、Hadleyのサイト、本、例を読んでいます。

第2の問題:審美的なアルファ設定は、背景を遮る矩形を妨げません。どのように透明性を取得するには?

dat <- data.frame(my_x_series=1:192, my_y_series=5.0*runif(192)) 
# (ymin, ymax are computed for this series using min/max(na.rm==TRUE)) 
ymax <- 5.0 
ymin <- 0.0 
p <- ggplot(dat, aes(x=my_x_series,alpha=0.9)) 
alternate_daily_bars_xmin <- c(4,52,100,148) 

for (shade_xmin in alternate_daily_bars_xmin) { 
    shade_xmax <- min(shade_xmin+24, 192) # clamp at end of x-range 
    p <- p + geom_rect(aes(alpha=0.5,xmin=shade_xmin,xmax=shade_xmax,ymin=ymin,ymax=ymax), fill='gray80') 
} 
p <- p + geom_point(aes(y=my_y_series)) 
p 
+0

は再現性のための*のDAT *のランダムな定義を追加しました。それは私を打つコマンド構文です。私はあなたが期待するかもしれないように、各geom_rectが合成の代わりに最後を上書きすると思います。 – smci

答えて

26

各行は単一の矩形の座標を含むデータフレームを作成し、自分の四角形をプロットします。この構造体は、矩形だけでなく、すべてのポリゴンで機能します。これを知ると、ループを回避するのは簡単です。

次に、変数を美的にマッピングするかどうかに注意してください。あなたの場合、alphaを任意の値に設定する必要があります。したがって、aes()設定の一部を構成しません。

library(ggplot2) 

dat <- data.frame(my_x_series=1:192, my_y_series=5.0*runif(192)) 
rect_left <- c(4,52,100,148) 
rectangles <- data.frame(
    xmin = rect_left, 
    xmax = rect_left + 24, 
    ymin = 0, 
    ymax = 5 
) 

ggplot() + 
    geom_rect(data=rectangles, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), 
      fill='gray80', alpha=0.8) + 
    geom_point(data=dat, aes(x=my_x_series, y=my_y_series)) 

enter image description here

+0

美しい。 * 'qplot()' *でこれを行うことができますか? – smci

+9

ほとんどすべてのものがありますが、私は 'qplot'で悩まされたことはありません。 'ggplot'は学ぶのが本当に難しいことではなく、あなたはいつもあなたが得るものを正確に知っています。ごめんなさい。 – Andrie

関連する問題