ggplot2 を使用して R で透明な背景のグラフを作成するにはどうすればよいでしょうか? 質問する

ggplot2 を使用して R で透明な背景のグラフを作成するにはどうすればよいでしょうか? 質問する

R から透明な背景の PNG ファイルに ggplot2 グラフィックを出力する必要があります。基本的な R グラフィックでは問題ありませんが、ggplot2 では透明になりません。

d <- rnorm(100) #generating random data

#this returns transparent png
png('tr_tst1.png',width=300,height=300,units="px",bg = "transparent")
boxplot(d)
dev.off()

df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y)) 
p <- p + opts(
    panel.background = theme_rect(fill = "transparent",colour = NA), # or theme_blank()
    panel.grid.minor = theme_blank(), 
    panel.grid.major = theme_blank()
)
#returns white background
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
p
dev.off()

ggplot2 で透明な背景を取得する方法はありますか?

ベストアンサー1

最初のプロットを作成します。

library(ggplot2)
d <- rnorm(100)
df <- data.frame(
  x = 1,
  y = d,
  group = rep(c("gr1", "gr2"), 50)
)
p <- ggplot(df) + stat_boxplot(
  aes(
    x = x,
    y = y,
    color = group
  ), 
  fill = "transparent" # for the inside of the boxplot
)

上記のプロットを完全に透明な背景に変更する最も簡単な方法は、theme()rect引数は、すべての長方形要素が から継承するものであるrect:

p <- p + theme(rect = element_rect(fill = "transparent"))
          
p

より制御された方法は、theme()のより具体的な引数を個別に設定することです。

p <- p + theme(
  panel.background = element_rect(fill = "transparent",
                                  colour = NA_character_), # necessary to avoid drawing panel outline
  panel.grid.major = element_blank(), # get rid of major grid
  panel.grid.minor = element_blank(), # get rid of minor grid
  plot.background = element_rect(fill = "transparent",
                                 colour = NA_character_), # necessary to avoid drawing plot outline
  legend.background = element_rect(fill = "transparent"),
  legend.box.background = element_rect(fill = "transparent"),
  legend.key = element_rect(fill = "transparent")
)

p

ggsave()専用の議論を提供しbg

背景色。 の場合NULLplot.backgroundプロット テーマの塗りつぶし値が使用されます。

透明な背景を使用してggplot オブジェクトをディスクpに書き込むには:filename

ggsave(
  plot = p,
  filename = "tr_tst2.png",
  bg = "transparent"
)

おすすめ記事