yihui / animation

A gallery of animations in statistics and utilities to create animations
https://yihui.org/animation/
206 stars 60 forks source link

Question: Transparent background #91

Open grssnbchr opened 7 years ago

grssnbchr commented 7 years ago

This is a question, not a bug report. I want to generate a GIF with ggplot2 and a transparent background. Even though I set the background to "transparent" in ggplot2's theme function, I don't get a transparent background in the final GIF. Is there an option which sets this? Or is this not even possible directly with saveGIF?

plotIteration <- function(frame) {
  current_df <- frame_dfs[[frame]]
  p <- ggplot() +
    geom_point(data = current_df, aes(x = lon, y = lat, alpha = I(alpha)), colour = "gray30", size = .2) +
    coord_equal() +
    theme(
      panel.background = element_rect(fill = "transparent", colour = NA) # bg of the panel
      , plot.background = element_rect(fill = "transparent", colour = 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", colour = NA) # get rid of legend bg
      , legend.box.background = element_rect(fill = "transparent", colour = NA) # get rid of legend panel bg
    )
  print(paste0("plotting frame ", frame))
  print(p)
}
saveGIF({
  for (frame in 1:frames){
    plotIteration(frame)
  }
}, interval = 0.03333, movie.name = "output/maps/3_10_1000_more_lateral_offset.gif")
yulijia commented 7 years ago

Hi, @grssnbchr

It is a little bit difficult for save GIF with ggplot2 and with a transparent background. You can try use im.convert() or gm.convert() in animation package.

Here is an example.

for (i in 1:10) {
  df=data.frame(x=1:10,y=rnorm(10, 1, 2))
  ggplot(df, aes(x = x, y = y))+
    geom_point()+  theme(  legend.background = element_rect(fill = "transparent"), # get rid of legend bg
                           legend.box.background = element_rect(fill = "transparent"),
                           panel.grid.minor = element_blank(),
                           panel.grid.major = element_blank(),
                           panel.background = element_rect(fill = "transparent",colour = NA),
                           plot.background = element_rect(fill = "transparent",colour = NA)
    )
  ggsave(paste0(tempdir(),"/Rplot",i,".png"),bg="transparent")
}

im.convert(files=file.path(tempdir(),"Rplot*.png"),output = "A.gif",extra.opts = "-dispose previous")

We will improve those functions for a better user experience in few weeks.

grssnbchr commented 7 years ago

Thank you, that basically works, yes. Looking forward to a package update though!

larsedler commented 6 years ago

I had the same issue. Use

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

This should give you the desired result.