2011-09-17 40 views
80

Necesito imprimir gráficos ggplot2 de R a archivos PNG con fondo transparente. Todo está bien con los gráficos básicos R, pero sin transparencia con ggplot2:¿Cómo hacer gráficos con fondo transparente en R usando 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 manera de obtener fondo transparente con ggplot2?

+0

Véase también [esta respuesta] (http://stackoverflow.com/questions/41856399/how-plot-transparent-background-ggplot), el sol actual es agregar 'theme (panel.background = element_rect (fill =" transparent ", color = NA), plot.background = element_rect (fill =" transparent ", color = NA))' –

Respuesta

72

También hay una opción de 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 cargada está mostrando de manera diferente que en mi equipo, así que he omitido él. Pero para mí, obtengo una trama con un fondo completamente gris a excepción de la parte de la caja de la gráfica de caja que todavía es blanca. Eso también se puede cambiar usando la estética de relleno en el Geom de Gráfica de caja, creo.

Editar

ggplot2 ya se ha actualizado y la función opts() ya no se utiliza. Actualmente, se utiliza en lugar de theme()opts() y element_rect() en lugar de theme_rect(), etc.

+0

No esperaba que lo hiciera trabaje con una Mac cuando se prueba con el PowerPoint actual de esa plataforma, pero funciona según lo anunciado. Y también funciona con pdf si quita las unidades y sustituye los tamaños en pulgadas. Buen trabajo. –

+1

Esto funciona excelente con MS Powerpoint 2010. En realidad, lo necesitaba para este propósito. –

+12

Si está usando ggsave, no olvide agregar 'bg =" transparent "' para pasar al dispositivo de gráficos png. – Tom

15

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 
) 

p <- p + 
    theme(
    panel.background = element_rect(fill = "transparent") # bg of the panel 
    , plot.background = element_rect(fill = "transparent") # 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 

o el uso de rect, ya que toda la elementos rectángulo heredan de rect:

p <- p + 
    theme(
    rect = element_rect(fill = "transparent") # bg of the panel 
) 
p 

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