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

Why does 2nd ggplot not appear using knitr and grid?

我正在尝试使用 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() 以允许两者都呈现。还必须调整边距才能显示注释。

Sp 你的密码是

\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}