wilkelab / ggtext

Improved text rendering support for ggplot2
https://wilkelab.org/ggtext/
GNU General Public License v2.0
655 stars 37 forks source link

Problem with text spacing (when using PDF device) #58

Closed PMassicotte closed 3 years ago

PMassicotte commented 3 years ago

First, thank you for the great package.

I am trying to make a graph using the ggtext package. I found out that the spacing between characters is off when I am saving the graphic using the PDF cairo device (I do not have this problem when saving to PNG).

library(tidyverse)
library(ggtext)
library(glue)
#> 
#> Attaching package: 'glue'
#> The following object is masked from 'package:dplyr':
#> 
#>     collapse

canada <- rnaturalearth::ne_states("canada", returnclass = "sf")

canada <- canada %>% 
  mutate(label = glue::glue("{sov_a3}<br><span style = 'font-size:4pt;'>{admin} 123456789</span>"))

ggplot() +
  geom_sf(data = canada) +
  facet_wrap(~label) +
  theme(
    strip.text = element_markdown(family = "Poppins")
  )

This is ok:

ggsave("~/Desktop/test.pdf", device = cairo_pdf)
#> Saving 7 x 5 in image

When saving using the PDF device, the spacing is wrong:

image

Created on 2020-12-07 by the reprex package (v0.3.0.9001)

clauswilke commented 3 years ago

Looks like Cairo doesn't know the font you're using. That's not a ggtext issue.

PMassicotte commented 3 years ago

It looks like the problem is related with the font size.

library(tidyverse)
library(ggtext)
library(glue)
#> 
#> Attaching package: 'glue'
#> The following object is masked from 'package:dplyr':
#> 
#>     collapse

ggplot() +
  annotate(
    "text",
    x = 1,
    y = 1,
    label = "123456789",
    family = "Poppins"
  ) +
  annotate(
    "richtext",
    x = 2,
    y = 1,
    label = "<span>123456789</span>",
    family = "Poppins",
    fill = NA,
    label.color = NA
  ) + 
  annotate(
    "richtext",
    x = 2,
    y = 0.975,
    label = glue::glue("<span style = 'font-size:10pt;'>123456789</span>"),
    family = "Poppins",
    fill = NA,
    label.color = NA
  ) +
  annotate(
    "richtext",
    x = 2,
    y = 0.976,
    label = glue::glue("<span style = 'font-size:4pt;'>123456789</span>"),
    family = "Poppins",
    fill = NA,
    label.color = NA
  ) +
  scale_x_continuous(expand = expansion(mult = c(1, 1)))

ggsave("~/Desktop/test.pdf", device = cairo_pdf)

If we zoom in, we see that the problem occurs when the font size is small.

image

Should I open an issue elsewhere?

Created on 2020-12-07 by the reprex package (v0.3.0.9001)

clauswilke commented 3 years ago

I would start with a posting on stackoverflow. Somebody may know of a way of fixing the issue.

PMassicotte commented 3 years ago

Thank you. As you said, probably not related to {ggtext}. I will close it. For reference:

https://stackoverflow.com/questions/65188058/font-spacing-whern-using-cairo-pdf-device

Thank you for your time.