【问题标题】:comfortable way to use unicode characters in a ggplot graph在 ggplot 图中使用 unicode 字符的舒适方式
【发布时间】:2015-01-01 09:13:01
【问题描述】:

在 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 设备的信息,但这会弄乱字体,我无法正确保存绘图。

提前感谢您的帮助。

编辑: Example PDF

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

【问题讨论】:

  • 我试过ggsave(file="newfile.pdf", device=cairo_pdf),在控制台上的版本和保存为pdf的版本之间没有发现太大的区别。
  • 如果您提供一些可重现的示例以便其他人可以检查可能会更好。
  • 我上传了一个示例 pdf...看起来,字体不会被嵌入或其他东西...我真的很想解决这个问题并在未来使用 unicode 字符!

标签: r unicode ggplot2


【解决方案1】:

试试

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

【讨论】:

  • 我没有加载 Cairo 库,但我的问题仍然存在...link 也许我应该提一下,我使用的是 MAC 系统
  • @user7601 我没有这个问题。我希望我可以分享我的pdf。在这里,我只能上传图像文件。我正在使用linux mint 17R 3.1.2
  • 哇,我用R 3.1.0... 好像在R 3.1.2 修复了... 所以不再在剧情中乱用unicode字符了!!!非常感谢阿克伦!
【解决方案2】:

使用emojifont 包为我解决了这个问题。

library(emojifont)

【讨论】:

  • 这可以无缝运行,无需担心版本号,谢谢!
【解决方案3】:

我正在分享使 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")

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 2011-06-25
    相关资源
    最近更新 更多