Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comfortable way to use unicode characters in a ggplot graph

Tags:

r

unicode

ggplot2

Is there a good practice to insert unicode characters in a ggplot title and also save it as pdf?

I am struggling with expression, paste and sprintf to get a nice title...

So, what works is

ggtitle(expression(paste('5', mu, 'g')))

This will print an ugly greek mu. By ugly I mean a different font, but overall, it will be printed as pdf without problems. But the problems start, if you want to have new lines in the title. Or maybe I didn't found a solution for this.

My preferred solution would be to use sprintf with the unicode number, so for example

ggtitle(sprintf('5\u03BCg'))

It shows a nice result on the screen but it is not possible to save as pdf with ggsave. PNG works fine, but I would like to use the pdf save option.

Is there a possibility to plot the unicode characters with ggsave? I read about the cairo_pdf device, but this messes up the fonts and I can not save the plot properly.

Thanks in advance for any help.

EDIT: Example PDF

I just uploaded an example PDF... So maybe my problem is somewhere else...

like image 902
drmariod Avatar asked Nov 05 '14 08:11

drmariod


2 Answers

Using the emojifont package fixes this issue for me.

library(emojifont)
like image 182
M. Galanakis Avatar answered Sep 30 '22 18:09

M. Galanakis


I am sharing the tricks to have Unicode characters properly displayed on PDF files. I am currently running R-4.0.5 for Windows.

library(ggplot2)
library(gridExtra)
library(grid)
library(png)

#--- The trick to get unicode characters being printed on pdf files:
#--- 1. Create a temporary file, say "temp.png"
#--- 2. Create the pdf file using pdf() or cairo_pdf(), say "UnicodeToPDF.pdf"
#--- 3. Combine the use of grid.arrange (from gridExtra), rasterGrob (from grid), and readPNG (from png) to insert the
#       temp.png file into the UnicodeToPDF.pdf file
test.plot = ggplot() +
  geom_point(data = data.frame(x=1, y=1), aes(x,y), shape = "\u2191", size=3.5) +
  geom_point(data = data.frame(x=2, y=2), aes(x,y), shape = "\u2020", size=3.5) +
  geom_point(data = data.frame(x=1.2, y=1.2), aes(x,y), shape = -10122, size=3.5, color="#FF7F00") +
  geom_point(data = data.frame(x=1.4, y=1.4), aes(x,y), shape = -129322, size=3.5, color="#FB9A99") +
  geom_point(data = data.frame(x=1.7, y=1.7), aes(x,y), shape = -128515, size=5, color="#1F78B4") +
  ggtitle(sprintf('5\u03BCg'))

ggsave("temp.png", plot = test.plot, width = 80, height = 80, units = "mm")
#--- Refer to http://xahlee.info/comp/unicode_index.html to see more unicode character integers

pdf("UnicodeToPDF.pdf")
grid.arrange(
  rasterGrob(
    readPNG(
      "temp.png",
      native=F
    )
  )
)
dev.off()

file.remove("temp.png")
like image 37
James Silva Avatar answered Sep 30 '22 19:09

James Silva