【问题标题】:Why does 2nd ggplot not appear using knitr and grid?为什么第二个 ggplot 没有使用 knitr 和 grid 出现?
【发布时间】:2016-01-04 18:42:25
【问题描述】:

我正在尝试使用 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()
  • 在第一个情节之后添加grid.newpage() 并没有改变任何东西。你想把它放在那个地方吗?在grid.draw(gt)之后?
  • 如果你只使用 ggplots,你会得到两个图(即省略所有网格的东西)
  • 是的。正如我所期望的那样,两个不同的情节。
  • hmmm,好吧...啊,刮一下——我用的是sweave而不是knitr

标签: r ggplot2 knitr r-grid


【解决方案1】:

从 cmets 添加代码

我在第二个绘图之前添加了一个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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-04
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多