I have added a font to my ggplot2-plot, and it works perfectly when viewed in RStudio's plot viewer. However, when I try to save the plot as a PDF, NO text at all is printed (see code and pictures below):
df <- data.frame(x = c(1:10), y = c(1:10)) # Dummy data
plot <- ggplot(df, aes(x, y)) + # Dummy plot
geom_point() +
labs(title = "Correct font in R, NO fonts at all in pdf :-(") +
theme(text = element_text(family = "latex"))
Then I try to ggsave() the plot with the following code:
ggsave("df_plot.pdf",
plot = plot,
device = "pdf",
dpi = 320)
But I get an error message:
Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, : invalid font type
Below is the plot with the correct fonts (in RStudio) + the plot that is written to my pdf file (with no fonts at all):
Plot with correct font Plot witn NO text
What am I missing here? I've tried various stuff with the extrafont package, but the pdfs don't print the fonts there either (if something is printed, its just the default fonts).
you may consider using the extrafont
package:
library(tidyverse)
library(extrafont)
fonts()
df <- data.frame(x = c(1:10), y = c(1:10)) # Dummy data
windowsFonts(Calibri = windowsFont("Calibri"))
plot <- ggplot(df, aes(x, y)) + # Dummy plot
geom_point() +
labs(title = "Correct font in R, NO fonts at all in pdf :-(") +
theme(text = element_text(size=15, family= "Tw Cen MT Condensed Extra Bold"))
ggsave("df_plot.pdf",
plot = plot,
device = cairo_pdf,
dpi = 320)
Actually, ggsave()
appears to work fine for me. The error is actually adding the theme(text = element_text(family = "latex"))
to the plot.
Adjusting the example a little bit,
df <- data.frame(x = c(1:10), y = c(1:10)) # Dummy data
plot <- ggplot(df, aes(x, y)) + # Dummy plot
geom_point() +
labs(title = "Correct font in R, NO fonts at all in pdf :-(")
ggsave("df_plot.pdf",
plot = plot,
device = "pdf",
dpi = 320)
#Saving 10.7 x 8.01 in image
But,
plot + theme(text = element_text(size=10, family="LM Roman 10"))
produces the error you've found:
Error in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : polygon edge not found.
This question has already been answered here: Error in grid.Call(L_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : Polygon edge not found
Do these suggestions work for you?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.