为什么使用knitr和grid时第二个ggplot没有出现?

4
我正在尝试使用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() - user20650
如果您只使用ggplots(即省略所有网格内容),您是否会得到两个图形? - user20650
嗯,好的...啊算了 - 我使用的是Sweave而不是Knitr。 - user20650
好的,使用 grid.newpage 在第二个绘图之前似乎可以正常工作。 - user20650
好的 Ceph,下面的代码展示了我添加这行代码的位置。 - user20650
显示剩余4条评论
1个回答

7

添加评论中的代码

在第二个图之前,我添加了一个grid.newpage()以允许两个图渲染。还必须微调边距才能显示注释。

您的代码如下:

\documentclass{article}

\begin{document}

<< fig.cap = c('color', 'clarity')>>=
library(ggplot2)
library(grid)

# 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) + 
theme(plot.margin=unit( c(2,1,1,1), "lines") ) ### added

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) + 
theme(plot.margin=unit( c(2,1,1,1), "lines") ) ### added

gs = ggplot_gtable(ggplot_build(q))
gs$layout$clip[gs$layout$name == 'panel'] = 'off'
grid.newpage() ## This is the extra line
grid.draw(gs)
@

\end{document}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接