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

时间:2016-01-04 18:42:26

标签: r ggplot2 knitr r-grid

我正在尝试使用knitr创建一个文档,其中包含使用ggplot2修改的grid个图。

在下面的示例中,使用diamonds中包含的ggplot2数据集,为2个图:第一个显示切割与颜色,第二个显示切割与清晰度。相反,后面的情节重复两次。第一个图不会在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)

来自两个数字,然后它们都会正确生成,但注释会被切断。

导致此问题的原因是什么,更重要的是,我该如何修复它?

谢谢!

1 个答案:

答案 0 :(得分:7)

从评论中添加代码

我在第二个绘图之前添加了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}