我正在尝试使用knitr
包含ggplot2
使用修改的图表创建文档grid
.
在下面的例子中,应该是2绘出使用既diamonds
包括在数据集ggplot2
:第一个显示切割与颜色和切断第二节目与清晰度.相反,后面的情节重复两次.根figure
目录中根本不生成第一个图.
\documentclass{article} \begin{document} <>= 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()
在第二个绘图之前添加了一个允许两个渲染.还必须调整边距以获得要显示的注释.
你的代码是
\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}