【问题标题】:bad font alignment using knitr and a non default font使用 knitr 和非默认字体的错误字体对齐
【发布时间】:2013-11-18 15:26:00
【问题描述】:

我有一些图形可以很好地直接打印为 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)

我明白了

这很好。然后转到 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

并且文本变得未对齐。

查看 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

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

我已经在 win7 和带有 R 3.0.1 的 MacOS X 平台上重现了这个问题

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

有什么建议吗?

【问题讨论】:

  • 您找到解决方案了吗?我观察到类似的行为,面板和绘图边距在 knitr 输出中被弄乱了,但在直接打印到 png 时工作正常。似乎 knitr 以某种方式应用了不同的主题,覆盖了指定的属性?!
  • 我终于使用了一个自制函数的解决方法,该函数直接调用 cairo_pdf 引擎并在 Markdown 文件中添加所有必要的代码。我在 knitr 中找不到解决方案。
  • @user2147028 我知道这是一篇旧帖子,所以希望你仍然活跃在这个网站上。我有描述的问题。如果您可以发布您的解决方法自制功能,这对于其他有同样问题的人来说真的很有帮助。也许把它放在你自己问题的答案中。您甚至可以将您的解决方案标记为最佳解决方案。

标签: r fonts knitr


【解决方案1】:

我不确定根本原因,但您可以通过调整主题的axis.title.y 元素中的vjust 参数来解决它。类似的东西

theme(
  text=element_text(family="Arial Unicode MS"),
  axis.title.y=element_text(family="Arial Unicode MS", vjust = 0)
)

【讨论】:

  • 这不起作用。标签现在未对齐到图的边缘。此外,我试图在这里举一个最小的例子,我的实际图表更复杂,并且未对齐会导致所有标签(x,y,条带,图例)出现问题。还是谢谢你的回答
猜你喜欢
  • 1970-01-01
  • 2019-04-19
  • 2017-12-10
  • 2013-04-24
  • 1970-01-01
  • 2016-02-27
  • 2021-02-06
  • 2018-10-13
  • 1970-01-01
相关资源
最近更新 更多