I am trying to create a document using knitr, which includes ggplot2graphics modified with grid.
In the example below, there should be 2 graphs using the dataset diamondsincluded in ggplot2: the first shows a reduction compared to color, and the second shows a reduction compared to clarity. Instead, the later schedule is repeated twice. The first chart is not generated in the directory figureat all.
\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'))
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)
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}
It is important if I delete the following lines:
gt = ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == 'panel'] = 'off'
grid.draw(gt)
from both figures , then both of them will be generated correctly, but the annotations will be cropped.
What causes this problem, and more importantly, how to fix it?
Thanks!