1

I have code that produces two separate ggplots and combines them into a single figure using gridExtra::grid.arrange.

I can save this combined figure as a PNG using ggsave(), but if I try to save it as an SVG file, I get only the second figure. How can I get both figures in one SVG file?

Edit: This question goes beyond that addressed in How to save a plot made with ggplot2 as SVG. ggsave() for SVG works well for single images, but DOES NOT WORK with SVG for images composed with grid.arrange.

Here is the figure I'm trying to create. Code for this example is below.

enter image description here

library(ggplot2)
library(gridExtra)
data(EastIndiesTrade,package="GDAdata")
c1 <- ggplot(EastIndiesTrade, aes(x=Year, y=Exports)) + 
             ylim(0,2000) + 
             geom_line(colour="black", size=2) + 
             geom_line(aes(x=Year, y=Imports), colour="red", size=2) +  
             geom_ribbon(aes(ymin=Exports, ymax=Imports), fill="pink",alpha=0.5) + 
             ylab("Exports and Imports (millions of pounds)") +
             annotate("text", x = 1710, y = 0, label = "Exports", size=5) +
             annotate("text", x = 1770, y = 1620, label = "Imports", color="red", size=5) +
             annotate("text", x = 1732, y = 1950, label = "Balance of Trade to the East Indies", color="black", size=6) +             
             theme_bw()
c2 <- ggplot(EastIndiesTrade, aes(x=Year,
             y=Imports-Exports)) + geom_line(colour="blue", size=2) +
             ylab("Balance = Imports - Exports (millions of pounds)") +
             geom_ribbon(aes(ymin=Imports-Exports, ymax=0), fill="pink",alpha=0.5) + 
             annotate("text", x = 1711, y = 30, label = "Our Deficit", color="black", size=6) +             
             theme_bw()

grid.arrange(c1, c2, nrow=1)

Now, I try to save them with ggsave():

ggsave("east-indies-ggplot2.png", width=10, height=4)  # OK
ggsave("east-indies-ggplot2.svg", width=10, height=4)  # not OK -- only get the right panel
user101089
  • 3,756
  • 1
  • 26
  • 53
  • Does this answer your question? [How to save a plot made with ggplot2 as SVG](https://stackoverflow.com/questions/12226822/how-to-save-a-plot-made-with-ggplot2-as-svg) – warnbergg Mar 03 '20 at 14:47

2 Answers2

2

you probably can try to use patchwork package

https://patchwork.data-imaginist.com instead of grid.arrange

Then you need to just use

c3=c1+c2
ggsave("~/Desktop/plotdm.svg")

This worked for me

Best

alb_alb
  • 58
  • 5
  • For the record: gridExtra::grid.arrange was somewhat of a kludge. `patchwork` is the way to go for this in future. – user101089 Mar 04 '20 at 20:52
0

You can do this if you put the grid.arrange call into the ggsave function as follows:

ggsave("east-indies-ggplot2.svg", plot = grid.arrange(c1, c2, nrow=1), width=10, height=4)

It will call grid.arrange and simultaneously save the svg.

ToWii
  • 590
  • 5
  • 8