I try to knit my Rmarkdown-file to a pdf-document. I get the following error:
Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
invalid character set type
This is the code I used:
comparison <- layout_with_fr(graph)
tidyclassroom <- as_tbl_graph(graph)
tidyclassroom %>%
activate("nodes") %>%
ggraph(layout=comparison) +
geom_edge_link(
end_cap = circle(12, "pt"),
color = "grey",
arrow = arrow(length=unit(5, "pt"))) +
geom_node_point(size=10, shape=21, fill=ifelse(V(graph)$sex == 2, "pink", "lightblue")) +
geom_node_text(aes(label = name), colour = 'black', vjust = 0.4) +
ggtitle('August 2023') +
theme_graph() +
theme(plot.title = element_text(hjust = 0.5))
For further explanation: I used an object called "comparison" because I have another network for another time point.
The code works when I don't use it in Rmarkdown. It also works as HTML (although I get some warning messages that I ignored).
I have read that it has something to do with the font type but I don't know how to solve this problem because I did not set the font size manually.
As you and @Julian already noted, this looks like a font issue. And the issue is that ggraph::theme_graph()
uses "Arial Narrow"
by default and which besides the error throws the following warnings:
In grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, : font family 'Arial Narrow' not found in PostScript font database
One option to fix that is to use e.g. the default "sans"
font by setting base_family = "sans"
.
Using the default example from ggraph
:
---
title: "Untitled"
output: pdf_document
date: "2024-08-24"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(ggraph)
library(tidygraph)
# Create graph of highschool friendships
graph <- as_tbl_graph(highschool) |>
mutate(Popularity = centrality_degree(mode = "in"))
# plot using ggraph
ggraph(graph, layout = "kk") +
geom_edge_fan(aes(alpha = after_stat(index)), show.legend = FALSE) +
geom_node_point(aes(size = Popularity)) +
facet_edges(~year) +
theme_graph(
base_family = "sans",
foreground = "steelblue", fg_text_colour = "white"
)
```
A second option which also worked fine for me is to use "cairo_pdf"
as the plotting device (which also worked for me even if the font is not available, e.g. I tested with base_family = "foobarbaz"
) which could be set using
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, dev="cairo_pdf")
```
And a third option which also worked fine for me (but requires that the font is available) is to use the extrafont
package as suggested in the R Graphics Cookbook.