Search code examples
rggplot2cairo

How to export high resolution ggplot graphic with unicode arrows


I am struggling to export the following ggplot2 graphic (legend) with Unicode arrows. This is the Plot Zoom output.

Text

The code used to create this legend is the following:

legend <- ggplot() +
  geom_tile(
    data = bivariate_color_scale,
    mapping = aes(
      x = gini,
      y = mean,
      fill = fill)
  ) +
  scale_fill_identity() +
  labs(y ="Higher bus. density →",
       x = "Higher patent growth →", 
       title = "Legend") +
  theme_minimal()+
  theme(
    panel.grid.minor = element_blank(), 
    panel.grid.major = element_blank(), 
    axis.line = element_blank(),
    axis.ticks = element_blank(),
    panel.border = element_blank(),
    axis.text.x = element_blank(),
    axis.text.y = element_blank() 
    ) +
  # make font small enough
  theme(axis.title = element_text(size = 8)) +
  # quadratic tiles
  coord_fixed()

I have tried to export this legend (in high resolution) with the following two codes:

ggsave(filename="legend.png", 
       plot = legend,
       dpi= 300,
       width = 210, 
       height = 180, 
       units = "mm")

and ...

ggsave(filename="legend.pdf",
       plot = legend, 
       dpi = 300, 
       device = cairo_pdf,
       width = 210, 
       height = 180, 
       units = "mm"
       )

Both codes did not properly translate/save the Unicode arrows (see the following output).

enter image description here

Does anybody have a suggestion on how I can export this graphic in high resolution with Unicode arrows? thank you in advance.


Data

bivariate_color_scale <- data.frame(gini = rep(1:3, 3), mean = rep(1:3, each = 3),
                                    fill = c("#beafc4", "#ae667c", "#9c263c",
                                             "#778fbd", "#6d5577", "#63233b",
                                             "#3970b3", "#354374", "#301d39"))

Solution

  • For display of Unicode characters you can use expression(), or (my preference) use sprintf(), then call the character inline with text using the preamble \u. See the following example:

    df <- data.frame(x=1:10, y=1:10)
    
    ggplot(df, aes(x,y)) + geom_point() +
      labs(
        title=paste("This Title has an up arrow!", sprintf('\u2191')),
        x=paste('The x axis goes this way:', sprintf('\u2794')),
        y=paste('The y axis is this way:',sprintf('\u2190'))
      )
    

    enter image description here