Cómo hacer gráficos con fondo transparente en R usando ggplot2?


Necesito generar gráficos ggplot2 de R a archivos PNG con fondo transparente. Todo está bien con gráficos R básicos, pero no hay transparencia con 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()

¿Hay alguna forma de obtener un fondo transparente con ggplot2?

Author: Yuriy Petrovskiy, 2011-09-17

2 answers

Actualizado con la función theme(), ggsave() y el código para el fondo de la leyenda:

df <- data.frame(y = d, x = 1, 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
  ) 

La forma más rápida es usar rect, ya que todos los elementos rectangulares heredan de rect:

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

La forma más controlada es usar las opciones de theme:

p <- p +
  theme(
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent", col = NA) # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank() # get rid of minor grid
    , legend.background = element_rect(fill = "transparent") # get rid of legend bg
    , legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
  )
p

Para salvar:

ggsave(p, filename = "tr_tst2.png",  bg = "transparent")
 26
Author: YCR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-16 13:50:31

También hay una opción plot.background además de panel.background:

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(),
    plot.background = theme_rect(fill = "transparent",colour = NA)
)
#returns white background
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
print(p)
dev.off()

Por alguna razón, la imagen subida se muestra de manera diferente que en mi computadora, por lo que la he omitido. Pero para mí, obtengo una trama con un fondo completamente gris, excepto por la parte de caja de la gráfica de caja que sigue siendo blanca. Eso también se puede cambiar usando la estética de relleno en la geomalla boxplot, creo.

Editar

Ggplot2 se ha actualizado y la función opts() ha sido obsoleto. Actualmente, usarías theme() en lugar de opts() y element_rect() en lugar de theme_rect(), etc.

 82
Author: joran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-03 01:04:34