我正在尝试使用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)
来自两个数字,然后它们都会正确生成,但注释会被切断。
导致此问题的原因是什么,更重要的是,我该如何修复它?
谢谢!
答案 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}