Chinese characters in ggplot on macOs

ggplot2

#1

A user of one of my R-packages reported issues with Chinese characters in titles when creating graphs. The graphs in the package are generated using ggplot2. It seems titles with Chinese characters are not displayed in ggplot in macOS. The same issue even showed up in base-R graphs (see examples below). Any suggestion on how to address this type of issue?

iris_cn <- iris
names(iris_cn) <- c("萼片长Sepal.Length","萼片宽Sepal.Width","花瓣长Petal.Length","花瓣宽Petal.Width","品种Species")
library(ggplot2)
ggplot(data = iris_cn, aes(x = 萼片长Sepal.Length)) + geom_histogram()

Histogram in base-R:

hist(iris_cn$萼片长Sepal.Length)

The user actually posted a “fix” as well, although it required changing the font-family. See below:

library(ggplot2)
theme < -theme_get()
#using the Chinese fonts you have, check it with font book.  
theme$text$family <- "STFangsong"
theme_set(theme)

iris_cn <- iris
names(iris_cn) <- c("萼片长Sepal.Length","萼片宽Sepal.Width","花瓣长Petal.Length","花瓣宽Petal.Width","品种Species")
library(ggplot2)
ggplot(data = iris_cn, aes(x = 萼片长Sepal.Length)) + geom_histogram()

image


#2

There’s an older post by @yihui on using Chinese characters in R graphics here:
https://yihui.name/cn/2007/06/chinese-characters-in-r-graphics/

There’s also a chapter on Chinese support in Peng Zhao’s R bookdownplus Textbook here:

Hopefully one of these is helpful!


#3

Basically it boils down to a single problem: you need an appropriate Chinese font. It is a hard problem, because unlike English and other western languages, there are not many choices for Chinese fonts on different platforms. It is hard to provide a portable solution. For example, STFangSong is a font only on macOS.

As long as you can find a Chinese font, the showtext package can be very helpful:

@mara Wow, you found a post I wrote more than 10 years ago! Even I almost forgot it. That post was primarily for Chinese characters in PDF and PostScript.


#4

Thanks for the suggestions. show_text looks great