1
votes

I have made a customized theme to a ggplot2 scatterplot, but when I try to save my plot to a PDF, the fonts go back to default font, and the grid lines and panel color also go back to default.

The question is: How can I get exactly what I see in my RStudio plot viewer to a high-res PDF?

Pictures: The first picture below shows what I want to have (how it looks in RStudio); the second picture shows the PDF with the wrong layout.

THIS is what I want (the RStudio plot),

THIS is what I want (the RStudio plot),

but THIS is what I get

but THIS is what I get.

The customized ggplot2-theme is as follows:

windowsFonts("latex" = windowsFont("CMU Serif")) 

mytheme <- theme(text = element_text(family = "latex"), 
             panel.grid.minor = element_blank(), 
             panel.grid.major = element_line(
               colour="grey97", 
               size = (0.01)), 
             panel.background= element_blank(),
             strip.text.x = element_text(size=12),
             strip.background = element_rect(fill="lightgrey",
                                             color = "black",
                                             size = 0.5),
             panel.border = element_rect(color = "black", 
                                         fill = NA, 
                                         size = 0.5))

And my ggsave-code is as follows:

ggsave("scatterplot.pdf", 
   plot = plot, 
   device = "pdf", 
   path = "[my path]",
   dpi = 320)

Is there anything I can add to the ggsave-code so that it can save the exact output from the RStudioplot?

1
please can you include the code you use to make the plot - Richard Telford
are you sure you are saving you plot as plot <- ggplot() + mytheme? before ggsave(plot) - tom

1 Answers

0
votes

Tom: It seems I hadn't saved the plot + theme before ggsave. So that did the trick -- thanks a lot :-)

However, now it seems to be a problem with (embedding) my font:

windowsFonts("latex" = windowsFont("CMU Serif"))

When I ggsave the plot to PDF using the same code above, no texts is printed, and only the first strip is printed (see the picture below), and I get the following error:

Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,: invalid font type

Bad plot

Here's the code for the plot, btw:

plot <- ggplot(ogna, aes(Birthyear, PRES_E)) +
geom_point(aes(fill = SJ_S), 
         shape = 21, 
         color = "black", 
         size = 3) +
scale_x_continuous(breaks = scales::pretty_breaks(n = 3), limits = c(1930, 2000)) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 5), limits = c(-5, 105)) +
facet_grid(. ~ Generation)