Yotta 資料視覺化實戰

ggplot2 中文字型設置

木刻思 - YJ

Mac

# 在最後加上
p + theme(text = element_text(family = "STHeiti"))

# 若有用到 geom_text 則要在裡面加 family = "STHeiti"
geom_text(family = "STHeiti")

輸出要設定 type = "cairo":

ggsave(device = "png", type = "cairo")`

範例:

library(ggplot2)
d <- data.frame(x=1:5, y=rnorm(5),
                label=c("一","二","三","四","五"))
p2 <- ggplot(d, aes(x, y)) +
  geom_point() +
  # geom_text 需要在裡面設定字型
  geom_text(aes(x=x+0.1, y=y-0.1, label=label, family="STHeiti")) +
  xlab("x軸") + ylab("y軸") +
  ggtitle("中文標題") +
  theme(text = element_text(family = "STHeiti"))  # here
p2

Linux

基本上沒問題

可用 fc-list 查看字型

Windows

基本上沒問題

# 在最後加上
p + theme(text = element_text(family = "微軟正黑體"))

# 或
p + theme(text = element_text(family = "Microsoft JhengHei"))