我正在尝试使用
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