Why does 2nd ggplot not appear using knitr and grid?

前端 未结 1 838
执念已碎
执念已碎 2021-01-19 16:01

I am trying to create a document using knitr that includes ggplot2 plots modified using grid.

In the example below, there

相关标签:
1条回答
  • 2021-01-19 16:15

    adding code from comments

    I added a grid.newpage() before the second plot to allow both to render. Also had to tweak the margins to get the annotations to show.

    Sp your code is

    \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}
    
    0 讨论(0)
提交回复
热议问题