这并不像看起来那么简单。从技术上讲,这个问题取决于 OS/locale/pdf writer/Sweave(参见“R 安装和管理”,第 7 章)。由于我运行的是 GNU/Linux,因此这个“解决方案”不适用于 Mac 和 Windows 用户。只是为了让事情变得更复杂一点,GNU/Linux 发行版有所不同,所以如果某些东西在 Ubuntu 上运行,很有可能在 Arch Linux 上不起作用。
我将使用mtcars
数据集。让我们创建一些带有本地化字符的基本图形:
pdf("foo.pdf")
boxplot(mpg ~ cyl, data = mtcars, ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja")
dev.off()
(塞尔维亚语速成课程:“Potrošnja goriva”代表油耗,“Broj cilindara”代表气缸数,“Dijagram raspršenja”相当于散点图)
现在,我收到一堆警告:
Warning messages:
1: In title(ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja") :
conversion failure on 'Dijagram raspršenja' in 'mbcsToSbcs': dot substituted for <c5>
2: In title(ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja") :
conversion failure on 'Dijagram raspršenja' in 'mbcsToSbcs': dot substituted for <a1>
3: In title(ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja") :
conversion failure on 'Dijagram raspršenja' in 'mbcsToSbcs': dot substituted for <c5>
4: In title(ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja") :
conversion failure on 'Dijagram raspršenja' in 'mbcsToSbcs': dot substituted for <a1>
5: In title(ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja") :
conversion failure on 'Potrošnja goriva' in 'mbcsToSbcs': dot substituted for <c5>
6: In title(ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja") :
conversion failure on 'Potrošnja goriva' in 'mbcsToSbcs': dot substituted for <a1>
7: In title(ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja") :
conversion failure on 'Potrošnja goriva' in 'mbcsToSbcs': dot substituted for <c5>
8: In title(ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja") :
conversion failure on 'Potrošnja goriva' in 'mbcsToSbcs': dot substituted for <a1>
虽然options(encoding = "CP1250")
不能解决问题 - 我得到相同的警告,pdf.options(encoding = "CP1250")
修复它,同样代表pdf(file = "foo.pdf", encoding = "CP1250")
. 因此,我将恢复我的旧编码,如前所述options(encoding = "native.enc")
设置并正确处理。pdf.options
有些用户只需设置 就可以逃脱pdf.options
,而使用 Sweave 则没有问题。因此,在开始绘图之前,您应该在 .Rnw 文件中的某处插入这部分代码:
<<setOptions, echo = FALSE, results = hide>>==
pdf.options(encoding = "CP1250")
@
稍后,只需执行以下操作:
<<plotTheFigure, echo = TRUE, fig = TRUE>>==
# I've set echo to TRUE intentionally, to prove my point here
boxplot(mpg ~ cyl, data = mtcars, ylab = "Potrošnja goriva", xlab = "Broj cilindara", main = "Dijagram raspršenja")
@
同样的场景也适用于 ggplot2 图。
你们中的一些人会得到正确的输出,但我没有!正如我之前所说,如果你运行的是 Ubuntu,那么这很有可能会起作用,但现在,我似乎无法让它在 Arch 中运行起来。
为了节省您的击键,您可以下载Sweave 文件和/或PDF 文件(在 Arch 机器上执行)。如您所见,本地化字符在绘图函数中正确显示,但在 Sweave 中出现乱码。现在,如果我尝试将图形保存到 PDF 文件(没有 Sweaving),我会得到正确的输出。
所以,我已经解决了一些问题,但是还有很多试错工作要做。
请在您的机器上运行 .Rnw 文件,并给我一些反馈。为了让事情变得简单,我创建了 Rscript 来收集我认为在这种情况下相关的系统信息(不是个人信息):here' the source,here's my output。