1

I'm trying to print a ggplot2 plot that contains a unicode character (specifically Japanese, but that shouldn't matter) to PDF. System locale is UTF8 on macOS, so I can use Unicode characters everywhere else. Unfortunately, ggsave only prints dots, not the characters. It's not really feasible to replace every individual character with its respective unicode code entry because it would just be too many. I've tried using Cairo as suggested below and in many other places, but that doesn't seem to work on macOS and R4.0.3, or maybe it used to work with earlier R versions but doesn't work anymore.

Save unicode characters to .pdf in R

library(ggplot2)
data("cars")

mpg$manufacturer[mpg$manufacturer == "nissan"] <- "日産"

carshwyplot <- ggplot(data=mpg, aes(x=manufacturer, y=hwy)) +
               geom_bar(stat="identity")

ggsave(filename = "carshwyplot.pdf", plot = carshwyplot,
       width = 12, height = 6, dpi = 300)
R version 4.0.3 (2020-10-10)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Big Sur 10.16

locale:
[1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8

This does not work for me, it just replaces the dots with square blocs.

library(Cairo)
ggsave(filename = "carshwyplot.pdf", plot = carshwyplot,
       width = 12, height = 6, dpi = 300, device = cairo_pdf)

Any suggestions?

2 Answers2

0

Add unicode font name such as Japan1.

ggsave(filename = "carshwyplot1.pdf", plot = carshwyplot,
       width = 12, height = 6, dpi = 300, device = cairo_pdf, Family = "Japan1")
Sinh Nguyen
  • 4,277
  • 3
  • 18
  • 26
Ken
  • 1
  • Hmm, that doesn't work for me. First it needs to be 'family' not 'Family' otherwise I get this error Error in dev(filename = filename, width = dim[1], height = dim[2], ...) : unused argument (Family = "Japan1") But even then the pdf output of the two characters is still just two blocs. – Irix3537106 Feb 01 '21 at 19:43
  • Oops!, family is correct. It works for me. May be my locale. Try this again. carshwyplot <- ggplot(data=mpg, aes(x=manufacturer, y=hwy)) + geom_bar(stat="identity") + theme_bw(base_family = "Osaka") . And, then, ggsave(filename = "carshwyplot.pdf", plot = carshwyplot, width = 12, height = 6, dpi = 300, device = cairo_pdf) – Ken Feb 03 '21 at 01:25
  • No luck. Same two blocs. The kanji are there in the plot window in RStudio, they just aren't in the PDF... – Irix3537106 Feb 04 '21 at 18:07
0

First, set your theme with unicode font family such as Osaka, HiraKakuProN-W3, etc. And, try device = Cairo_pdf.

` carshwyplot <- ggplot(data=mpg, aes(x=manufacturer, y=hwy)) + geom_bar(stat="identity") + theme_bw(base_family = "Osaka")

ggsave(filename = "carshwyplot.pdf", plot = carshwyplot, width = 12, height = 6, dpi = 300, device = cairo_pdf)`

Ken
  • 1