在 R 中将 unicode 字符保存为 .pdf

Save unicode characters to .pdf in R

我想用 ggsave.

将特定的 unicode 字符保存到 pdf 文件

示例代码

library(ggplot2)

ggplot() +
  geom_point(data = data.frame(x=1, y=1), aes(x,y), shape = "\u2191") +
  geom_point(data = data.frame(x=2, y=2), aes(x,y), shape = "\u2020")

ggsave("test.pdf", plot = last_plot()), width = 40, height = 40, units = "mm")

但是,当保存 .pdf 时,unicode 字符被转换为三个点...

尝试修复它

  1. 我尝试在 ggsave 中使用 cairo_pdf 设备 -> 没用。
  2. 用这个post画了unicode字符,但是没看懂...

问题

如何在 pdf 中使用两个 unicode 字符?

> sessionInfo()
R version 3.6.2
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Catalina 10.15.5

这似乎适用于我的 mac:

library(tidyverse)

quartz(type = 'pdf', file = 'test.pdf')

ggplot() +
    geom_point(data = data.frame(x=1, y=1), aes(x,y), shape = "\u2191") +
    geom_point(data = data.frame(x=2, y=2), aes(x,y), shape = "\u2020")

使用此处的建议:

对 unicode 字符和 pdf 使用 ggsave() 有点敏感。尝试显式 post 到设备。当我使用 pdf() 时,它对我不起作用,但使用 cairo_pdf() 时有效。

p <- ggplot() +
  geom_point(data = data.frame(x=1, y=1), aes(x,y), shape = "\u2191", size=4) +
  geom_point(data = data.frame(x=2, y=2), aes(x,y), shape = "\u2020", size=4)

然后比较这些:

# using pdf() gives me warnings and does not work
pdf('test.pdf')
print(p)
dev.off()

# using cairo_pdf() works
pdf('test_cairo.pdf')
print(p)
dev.off()

欢迎您在这里查看我对类似问题的回答:

但这里是您问题的解决方案。

#--- A function to install missing packages and load them all
myfxLoadPackages = function (PACKAGES) {
  lapply(PACKAGES, FUN = function(x) {
    if (suppressWarnings(!require(x, character.only = TRUE))) {
      install.packages(x, dependencies = TRUE, repos = "https://cran.rstudio.com/")
    }
  })
  lapply(PACKAGES, FUN = function(x) library(x, character.only = TRUE))
}

packages = c("ggplot2","gridExtra","grid","png")
myfxLoadPackages(packages)

#--- 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")
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")

已添加下图以跟进 Konrad Rudolph 的评论。