LoginSignup
16
17

More than 5 years have passed since last update.

ggplot2で透明な背景にする方法

Last updated at Posted at 2015-09-09

2016/04/12追記: ggplot2 v2.1.0にて動作を確認しました

Q

ggplot2で作成したグラフィックを、背景が透明なPNGに出力する必要があります。基本Rグラフィックならうまくいくのですが、ggplot2だと透明になりません:

d <- rnorm(100) #ランダムデータ生成

# これなら透明背景のPNGができます
png('tr_tst1.png',width=300,height=300,units="px",bg = "transparent")
boxplot(d)
dev.off()

# ggplot2でオブジェクト作成
df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x=x,y=y)) 
p <- p + theme(
    panel.background = element_rect(fill = "transparent",color = NA),
    panel.grid.minor = element_line(color = NA), 
    panel.grid.major = element_line(color = NA)
)
# でもこれだと背景が白くなります
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
p
dev.off()

※ 評価させていません

ggplot2で透明背景を出力させる方法はあるのでしょうか。

A

上記のtheme()設定では、plot.backgroundを透明指定していません。まずは以下のようにggplot2のオブジェクトを作成します:

d <- rnorm(100)
df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y)) 
p <- p + theme(
    panel.background = element_rect(fill = "transparent",color = NA),
    panel.grid.minor = element_line(color = NA), 
    panel.grid.major = element_line(color = NA),
    plot.background = element_rect(fill = "transparent",color = NA)  #ここを追加
)
p

OK_example1.R-1.png

これで、背景要素が透明になります。これをPNG形式に出力するにはggsaveが便利です:

ggsave("tr_tst3.png", p, bg = "transparent")

※ 評価させていません

?ggsaveにはbgという引数はありませんが、その他の引数はこの場合graphics deviceにそのまま送られるため、透明処理が働きます。逆にこの引数を設定しないと透明にならず白色になります。

また、knitrなどで出力する場合には、チャンクオプションとしてdev.args=list(bg='transparent)の記述が必要です:

{r hogehoge, dev.args = list(bg = 'transparent')}

この際も、出力するggplot2のオブジェクトには、背景要素を全て透明に設定しておいてください。

参照

この記事は、StackOverflowに投稿された以下の記事を参考に、現在のggplot2のバージョンにあうようにコードを編集し、一部内容を変更して作成しました:
- How to make graphics with transparent background in R using ggplot2? - Stack Overflow

関連記事・ドキュメント:
- How to use a "R-generated" plot as a semi-transparent background in an HTML5 slide made by knitr? - Stack Overflow
- theme. ggplot2 0.9.3.1

16
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
17