Home > Software engineering >  how to ggsave rotated plot
how to ggsave rotated plot

Time:10-16

I try to save plots with different angles (want to use it later for an animation in beamer). I tried this:

data=data.frame(x=rnorm(100)) # creates the data
plot <- ggplot2::qplot(x, data=data, geom="histogram") # create a histogram  

for(i in seq(-90, 0, by = 30)){ # sequence of angles
print(plot, vp=grid::viewport(angle=i)) # rotate with differen angles
ggplot2::ggsave(paste0("plots/plot_", i, ".png")) # save every plot with the name of the angle
}

The Warning is: Warning: cannot clip to rotated viewport

How can I clip the viewport correctly?

CodePudding user response:

Ggsave saves the last plot that you displayed over this function. In your case, print is treated as a base plot, so it will be saved the same way.

Try this loop instead:

for(i in seq(-90, 0, by = 30)){ # sequence of angles
  png(paste0("plot_", i, ".png"), width = 500, height = 500) # open the file
  pushViewport(viewport(name = "rotate", angle = i, clip = "off", width = 0.7, height = 0.7))
  print(plot, vp="rotate") # rotate with differen angles
  dev.off() # close the file
}

Output:

enter image description here

  • Related