Reputation: 2259
We can make a ggplot
object and change its font with the showtext
package.
library(ggplot2)
library(showtext)
library(officer)
library(rvg)
p1 <- ggplot(mtcars, aes(x = cyl)) +
geom_bar() +
ggtitle("A B C D")
font_add_google("Poppins")
showtext_auto()
p2 <- p1 + theme(text = element_text(family = "Poppins"))
This yields an image that looks as expected.
Yet, if I next use the officer
and rvg
packages to print the same plot
as an editable vector graphics element within a .pptx file, something goes awry.
pptx <- read_pptx()
pptx <- add_slide(pptx, layout = "Blank", master = "Office Theme")
pptx <- ph_with(x = pptx, value = dml(ggobj = p2), location = ph_location(width=6, height=6))
print(pptx, target = "Slide_ABCD.pptx")
The characters in the plot end up being "filled in". This problem does not appear when you use the default ggplot2
fonts.
The ?rvg::dml
documentation says this about the fonts
argument:
Named list of font names to be aliased with fonts installed on your system. If unspecified, the R default families sans, serif, mono and symbol are aliased to the family returned by match_family().
When you use specific fonts, you will need that font installed on your system. This can be check with package gdtools and function gdtools::font_family_exists().
When I run gdtools::font_family_exists("Poppins")
, it returns TRUE
I've tried to specify "Poppins" and "Poppins-Regular" in the rvg:dml()
call, like this:
pptx <- ph_with(x = pptx, value = dml(ggobj = p2, fonts = list(sans = "Poppins", serif = "Poppins", mono = "Poppins")), location = ph_location(width=6, height=6))
But these steps don't change the output. I still get "filled in" font.
I am aware that one can insert an image file into these pptx outputs, but I really need the output to be an editable vector graphics element.
Any ideas for how I can fix this problem so the editable vector graphics element font looks like the image font?
Upvotes: 0
Views: 137
Reputation: 2259
My solution to the "filled text" problem is to use the extrafont
package, instead of showtext
.
Once the font is imported and loaded, it is rendered correctly in the ggplot and in the editable vector graphics element.
# only need to be done once!!!
extrafont::font_import(pattern = "Poppins-Regular.ttf")
# do this in each session
extrafont::loadfonts()
p2 <- p1 + theme(text = element_text(family = "Poppins"))
pptx <- read_pptx()
pptx <- add_slide(pptx, layout = "Blank", master = "Office Theme")
pptx <- ph_with(x = pptx,
value = dml(ggobj = p2),
location = ph_location(width=6, height=6))
print(pptx, target = "Slide_ABCD.pptx")
```
Upvotes: 0