【问题标题】:Controlling placement of figures with the knitr::include_graphics function使用 knitr::include_graphics 函数控制图形的放置
【发布时间】:2017-04-17 09:06:04
【问题描述】:

我在*.Rmd 文件中使用以下代码来生成以下输出:

```{r gb, echo=F, eval=T, results='asis', cache.rebuild=T, fig.cap='bla', out.width='0.7\\linewidth', fig.subcap=c('bla.', 'Using the \\textit{normalizeChIPToInput} function. THis method doesn not require to compute a enrichment ratio.')}
p1 <- file.path(FIGDIR, 'correlK27K9me3.png')
p2 <- file.path(FIGDIR, 'correlK27K9me3.png')
knitr::include_graphics(c(p1,p2))
```

我想垂直堆叠这两个图而不是并排显示它们而不单独调用include_graphics(这不适用于子标题)并且不必将它们单独放置大块。这是否可以在不操作乳胶代码的情况下实现?

更一般地说,是否可以以某种方式指定以上述方式包含的绘图的布局,例如:'给我一个 2x2 的网格,用于我提供给 include_graphics 函数的 4 张图像?

【问题讨论】:

  • 如果@Yihui 没有答案,我怀疑这很容易/可能。一个复杂的问题是,这种建议的布局不容易在knitr 支持的所有格式中移植。由于您正在争夺 pdf 输出,也许您可​​以在 Rmd 文件中使用文字 LaTeX 代码来做您想做的事情。
  • 我无法重现您的示例。您能否提供您的 png 文件和 YAML 标头?
  • 你有没有想过直接在文档中放置 HTML 代码来处理这个问题?当然,假设您正在编译为 HTML。

标签: r knitr r-markdown


【解决方案1】:

这不是问题的最巧妙的解决方案,而是在 R 中使用 gridarrangetext 函数的一个小解决方法。

流程 : read_images -> 转换为网格 -> 读取网格图像 -> add_text -> final_save

```{r fig.align='center', echo=FALSE, fig.cap="Figure 1 : foo", warning=FALSE, message=FALSE}
library(png)
library(grid)
library(gridExtra)

#Loading images
img0 <- readPNG("heatMap.png")
img1 <- readPNG("heatMap.png")
img2 <- readPNG("heatMap.png")
img3 <- readPNG("heatMap.png")

#Convert images to Grob (graphical objects)
grob0 <- rasterGrob(img0)
grob1 <- rasterGrob(img1)
grob2 <- rasterGrob(img2)
grob3 <- rasterGrob(img3)

png(filename = "gridPlot.png", width = 1200, height = 716)

grid.arrange(grob0, grob1, grob2, grob3, nrow = 2)

invisible(dev.off())

gridplot.0 <- readPNG("gridPlot.png")
h<-dim(gridplot.0)[1]
w<-dim(gridplot.0)[2]

png(filename = "gridPlotFinal.png", width = 1200, height = 716)

#adding text to image (refer to https://stackoverflow.com/a/23816416/6779509)

par(mar=c(0,0,0,0), xpd=NA, mgp=c(0,0,0), oma=c(0,0,0,0), ann=F)
plot.new()
plot.window(0:1, 0:1)

#fill plot with image
usr<-par("usr")    
rasterImage(gridplot.0, usr[1], usr[3], usr[2], usr[4])

#add text
text("plot1", x=0.25, y=0.50)
text("plot2", x=0.75, y=0.50)
text("plot3", x=0.23, y=0.0)
text("plot4", x=0.77, y=0.0)

invisible(dev.off())

gridplot <- file.path("gridPlotFinal.png")
knitr::include_graphics(gridplot)
```

输出:

【讨论】:

    【解决方案2】:

    代替:

    knitr::include_graphics(c(p1,p2))
    

    这个呢:

    cowplot::plot_grid(p1, p2, labels = "AUTO", ncol = 1, align = 'v')
    

    这将在 {r} 内部工作,但我不确定根据您的块配置/设置它将如何工作。

    【讨论】:

      猜你喜欢
      • 2018-04-19
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 2021-10-10
      • 1970-01-01
      相关资源
      最近更新 更多