Search code examples
rggplot2ggtext

ggtext formatting getting messed up with ggsave


I am using ggtext::element_textbook_simple to include a bit of filler text in a plot as it has great functionality around word wrapping for long strings.

When I run the code directly in markdown, I get a nice plot with even spacing between all words:

```{r fig.width = 6, fig.height = 4}
library(dplyr)
library(ggplot2)
library(ggtext)

p1 <- mtcars %>% 
  ggplot(aes(x = wt, y = hp)) +
  geom_point() +
  labs(title = "This is a Generic Title",
       subtitle = "The theme song and opening sequence set the premise of the show. Will Smith is a street-smart teenager, West Philadelphia born and raised. While playing street basketball, Will misses a shot and the ball hits a group of gang members, causing a confrontation that frightens his mother, who sends him to live with his wealthy aunt and uncle in the opulent neighborhood of Bel Air, Los Angeles. Will's working class background ends up clashing in various humorous ways with the upper class world of the Banks family – Will's uncle Phil and aunt Vivian and their children, Will's cousins: spoiled Hilary, pompous Carlton, and impressionable Ashley.") + 
  theme(plot.title.position = "plot",
        plot.subtitle = element_textbox_simple(size = 10, lineheight = 1, padding = margin(5, 1, 5, 1)))

p1
```

enter image description here

However, when I use ggsave to export the plot with the same dimensions, suddenly I get lots of spacing errors with the words:

ggsave("plot1.png", p1, width = 6, height = 4)

enter image description here

Does anyone know why this is the case/how I can prevent this from happening?


Solution

  • It's probably the graphics device. I can't reproduce the issue on my end. Try the agg device.

    library(ragg)
    
    agg_png("plot1.png", width = 6, height = 4, units = "in", res = 300)
    print(p1)
    dev.off()