提问者:小点点

在GGPLANT图形中使用Unicode字符的舒适方法


在ggplot标题中插入unicode字符并将其另存为pdf是否是一种良好的做法?

我正在努力与表达,粘贴和sprintf获得一个好的标题。。。

所以,有效的是

ggtitle(expression(paste('5', mu, 'g')))

这将打印一个丑陋的希腊亩。我说的丑是指一种不同的字体,但总的来说,它会被打印成PDF格式,没有问题。但是问题开始了,如果你想在标题中有新的行。或者也许我没有找到解决办法。

我的首选解决方案是将sprintf和unicode数字一起使用,例如

ggtitle(sprintf('5\u03BCg'))

它在屏幕上显示了一个很好的结果,但无法使用ggsave保存为pdf。PNG工作正常,但我想使用pdf保存选项。

是否可以使用ggsave打印unicode字符?我读到了cairo_pdf设备,但这会弄乱字体,我无法正确保存绘图。

提前感谢您的帮助。

编辑:PDF示例

我刚刚上传了一个示例PDF...所以也许我的问题在别的地方...


共3个答案

匿名用户

尝试

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)
set.seed(42) 
df <- data.frame(date = 1:10 , value = cumsum(runif(10 , max = 10)) )

匿名用户

使用emojifont包可以修复此问题。

library(emojifont)

匿名用户

我分享的技巧,有Unicode字符正确显示在PDF文件。我目前运行的Windows的R-4.0.5。

library(ggplot2)
library(gridExtra)
library(grid)
library(png)

#--- 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") +
  ggtitle(sprintf('5\u03BCg'))

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