【发布时间】:2016-01-04 18:42:25
【问题描述】:
我正在尝试使用 knitr 创建一个文档,其中包含使用 grid 修改的 ggplot2 绘图。
在下面的示例中,应该有 2 个图都使用 ggplot2 中包含的 diamonds 数据集:第一个显示切工与颜色,第二个显示切工与净度。相反,后面的情节重复了两次。第一个图根本没有在figure 目录中生成。
\documentclass{article}
\begin{document}
<<fig.cap = c('color', 'clarity')>>=
library(ggplot2)
library(grid)
theme_update(plot.margin = unit(c(1.5, 2, 1, 1), 'lines'))
# Create plot with color
p = ggplot(diamonds,aes(cut,fill = color)) + geom_bar(position = 'fill') + annotate('text', label = as.character(table(diamonds$cut)), x = 1:5, y = Inf, vjust = -1)
gt = ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == 'panel'] = 'off'
grid.draw(gt)
# Create plot with clarity
q = ggplot(diamonds,aes(cut,fill = clarity)) + geom_bar(position = 'fill') + annotate('text', label = as.character(table(diamonds$cut)), x = 1:5, y = Inf, vjust = -1)
gs = ggplot_gtable(ggplot_build(q))
gs$layout$clip[gs$layout$name == 'panel'] = 'off'
grid.draw(gs)
@
\end{document}
重要的是,如果我删除以下行:
gt = ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == 'panel'] = 'off'
grid.draw(gt)
来自两个图,那么它们都将正确生成,但注释将被切断。
是什么导致了这个问题,更重要的是,我该如何解决?
谢谢!
【问题讨论】:
-
你可能需要
grid.newpage() -
在第一个情节之后添加
grid.newpage()并没有改变任何东西。你想把它放在那个地方吗?在grid.draw(gt)之后? -
如果你只使用 ggplots,你会得到两个图(即省略所有网格的东西)
-
是的。正如我所期望的那样,两个不同的情节。
-
hmmm,好吧...啊,刮一下——我用的是sweave而不是knitr