Numerous people have had the issue where a custom font shows up in the ggplot but disappears upon export using ggsave
, but I've only ever found solutions to this for exporting pdfs (e.g. ggplot embedded fonts in pdf). I'm trying to export as png. This has previously worked fine for me, so not sure what's going on.
Just updated everything, which didn't fix the issue - R is version 3.5.0; RStudio is 1.1.453; on macOS Sierra.
Both of these work to add the font to the plot:
1:
if (!require(showtext)) {
install.packages("showtext", repos = "http://cran.utstat.utoronto.ca/")
require(showtext)
}
font_add_google("Karla", "karla") # Add nice google font
showtext_auto() # Tell R to use showtext to render google font
2:
if (!require(extrafont)) {
install.packages("extrafont", repos = "http://cran.utstat.utoronto.ca/")
require(extrafont)
}
font_import(pattern = "Karla")
How I'm plotting it:
theme_map <- function(...) {
theme_minimal() +
theme(
text = element_text(family = "Karla", color = "#22211d"),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
plot.background = element_rect(fill = "#f5f5f2", color = NA),
panel.background = element_rect(fill = "#f5f5f2", color = NA),
legend.background = element_rect(fill = "#f5f5f2", color = NA),
panel.border = element_blank(), # infuriatingly doesn't work but that's unrelated
aspect.ratio = 9 / 16, # 16:9 aspect ratio
...
)
}
data(iris)
p <- ggplot() + geom_point(data=iris, aes(x=iris$Sepal.Length, y=iris$Sepal.Width)) + labs(title="Font Pls") + theme_map()
plot(p)
ggsave("iris.png", p, device="png")
ggsave("iris.png", p, device="png", type="cairo") # does not produce an error but also doesn't produce a .png file
ggsave("iris.png", p, device="cairo-png") # also does not produce an error but also doesn't produce a .png file
What I see in RStudio (and want to save):
What gets saved using ggsave:
This is what is spit out using ggsave
, even with solutions provided elsewhere like type = "cairo-png"
or type = "cairo"
. (Adding either of those just gives an error, doesn't save the plot at all.) Not sure if it's related (though it probably is), but ggsave also appears to be ignoring the text sizes and italics for the title, axes, etc.
I'm happy to use a non-ggsave solution if it's out there. I have hundreds of images I need to export in this format so "export it as a pdf then save as a png" is not an option.