使用knitr和非默认字体进行错误的字体对齐

时间:2013-11-07 04:50:11

标签: r fonts knitr

我有一些图形可以很好地直接打印输入为R代码,但是当由knitr生成时会产生错误的文本对齐。 考虑

library(ggplot2)
library(extrafont)
loadfonts(device="win")
ggplot(data.frame(x=1:10,section=c(rep("You",8),rep("Me",2))))+
geom_point(aes(x=x,y=x))+
ylab("my\nlabel")+
theme(text=element_text(family="Arial Unicode MS"))+facet_wrap(~section)

我得到了

plot1

哪个好。然后转到knitr(带有R降价)

```{r dev=c('png')}
library(ggplot2)
library(extrafont)
loadfonts(device="win")
ggplot(data.frame(x=1:10,section=c(rep("You",8),rep("Me",2))))+
geom_point(aes(x=x,y=x))+
ylab("my\nlabel")+
theme(text=element_text(family="Arial Unicode MS"))+facet_wrap(~section)
```

我得到一些警告(好几次)

## Warning: unknown AFM entity encountered
## Warning: font width unknown for character 0x32

并且文字变得不对齐。

plot2

看看y标签。

我使用cairo_pdf设备

时遇到了完全相同的问题

代码变为

library(ggplot2)
cairo_pdf("plot.pdf")
ggplot(data.frame(x=1:10,section=c(rep("You",8),rep("Me",2))))+
geom_point(aes(x=x,y=x))+
ylab("my\nlabel")+
theme(text=element_text(family="Arial Unicode MS"))+facet_wrap(~section)
dev.off()
对于R,

```{r dev=c('cairo_pdf')}
library(ggplot2)
ggplot(data.frame(x=1:10,section=c(rep("You",8),rep("Me",2))))+
geom_point(aes(x=x,y=x))+
ylab("my\nlabel")+
theme(text=element_text(family="Arial Unicode MS"))+facet_wrap(~section)
```

针织者。警告现在是

## Warning: font family 'Arial Unicode MS' not found in PostScript font database

但图片显示与以前相同的问题。

我在使用R 3.0.1的win7和MacOS X平台上重现了这个问题

我想可能有一个简单的解决方案来解决这个问题,但我没有设法解决这个问题。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我不确定根本原因,但您可以通过调整主题的vjust元素中的axis.title.y参数来修复它。像

这样的东西
theme(
  text=element_text(family="Arial Unicode MS"),
  axis.title.y=element_text(family="Arial Unicode MS", vjust = 0)
)