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.
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