comfortable way to use unicode characters in a ggp

2019-06-19 00:50发布

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...

1条回答
别忘想泡老子
2楼-- · 2019-06-19 01:39

Try

library(ggplot2)
p <- ggplot(df, aes(x=date, y=value)) 
p <- p + geom_line()
p + ggtitle(sprintf('5\u03BCg'))
library(Cairo)
ggsave("newfile.pdf", device=cairo_pdf)

data

set.seed(42) 
df <- data.frame(date = 1:10 , value = cumsum(runif(10 , max = 10)) )
查看更多
登录 后发表回答