自定义ggplot字体与sweave和beamer

时间:2016-07-28 12:15:32

标签: r ggplot2 fonts sweave beamer

我想在.Rnw投影仪演示文稿中使用自定义字体。重现错误的最小工作示例是:

\documentclass{beamer}
\begin{document}
\begin{frame}[plain]
<<echo=FALSE>>= 
library(ggplot2)
library(extrafont)
@
\begin{figure}
\centering
<<label = test, fig=TRUE, include=FALSE, echo=FALSE, message=FALSE>>=
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme_bw() +
  theme(text=element_text(family="Garamond", size=14))
@
\includegraphics[width=\textwidth]{test}
\end{figure}
\end{frame}
\end{document}

,错误消息如下所示:

Writing to file test.tex
Processing code chunks with options ...
 1 : keep.source term verbatim (test.Rnw:6)
Registering fonts with R
 2 : keep.source term verbatim pdf  (label = test, test.Rnw:12)
Error in grid.Call.graphics(L_text, as.graphicsAnnot(x$label), x$x, x$y,  : 
  invalid font type
Calls: <Anonymous> ... drawDetails -> drawDetails.text -> grid.Call.graphics
In addition: There were 50 or more warnings (use warnings() to see the first 50)
Execution halted

但是当我在控制台中使用ggplot命令时,一切看起来都很好。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

好吧,问题确实是没有安装字体。但由于我只使用Garamond作为一个例子并且真的想使用otf字体Fira Sans,我使用了showtext包。

以下是有效的代码:

\documentclass{beamer}
\begin{document}
\begin{frame}[plain]
<<test, fig=TRUE, echo=FALSE, width=6, height=4>>=
library(ggplot2)
library(showtext)
font.add.google("Fira Sans", "fira")
showtext.auto()
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme_bw() +
  theme(text = element_text(family = "fira"))
@
\end{frame}
\end{document}