簡體   English   中英

Rmarkdown中的循環:如何制作文本中的圖形參考? 配圖?

[英]Loops in Rmarkdown: How to make an in-text figure reference? Figure captions?

{r setup, include=FALSE, message=FALSE, results="hide"} knitr::opts_chunk$set(echo = TRUE) library(knitr) library(kfigr) library(dplyr) library(png) library(grid) library(pander) library(ggplot2)

rmarkdown中的循環:文本中的圖形參考? 配圖?

目標

使用for循環可以在圖表列表中創建包含文本,文本內結果和多個圖形引用以及相關圖形標題的部分。 在這些新部分之前和之后編號的數字,圖形參考/編號應該是無縫的。

注意: for循環中引用的數字在文本的前面生成,保存為png,然后重新加載。 對於這個例子來說,這看起來很笨拙,但是實際的無花果是地圖並且生成起來很慢(我計划在我擁有它們之后注釋出生成數字的循環)。

{r echo = FALSE, warnings=FALSE, message=FALSE, results="hide"}

數據:每年我們都有不同數量的階層,因此需要循環。

df <- rbind(
  data.frame(strata = rep("A", 10), x = rnorm(10, mean= 10), y = rnorm(10, mean = 15),z = rnorm(10, mean = 20)),
  data.frame(strata = rep("B", 10), x = rnorm(10, mean= 5), y = rnorm(10, mean = 10), z = rnorm(10, mean = 15)),
  data.frame(strata = rep("C", 10), x = rnorm(10, mean= 15), y = rnorm(10, mean = 20), z = rnorm(10, mean = 10)))

first_plot:在for循環之前應該出現在列表中的數字按分層創建部分

first_plot <- ggplot(df, aes(x, fill=strata)) + geom_histogram()

last_plot:在for循環之后應該出現在列表中的數字按層次創建部分

last_plot <- ggplot(df, aes(x = strata, y = z)) + geom_boxplot()

圖生成(這是我的版本稍后將被注釋掉的部分,一旦我有了我想要的地圖)

strat <- unique(df$strata)

for (i in seq_along(strat)) {
  sub <- df %>% filter(strata %in% strat[i])
  fig1 <- ggplot(sub, aes(x = x, y = y)) + geom_point()
  ggsave(fig1, file=paste0("fig1_", strat[i], ".png"))
  fig2 <- ggplot(sub, aes(x = x, y = z)) + geom_point() 
  ggsave(fig2, file=paste0("fig2_", strat[i], ".png"))
}    

加載png

df_figs <- list.files(pattern = "\\.png$")
for (i in df_figs){  
   name <- gsub("-",".",i)
   name <- gsub(".png","",name)  
   i <- paste(".\\",i,sep="")
   assign(name,readPNG(i))
}

介紹部分

報告中的一些介紹性文字和圖r figr('first_plot',TRUE, type='Figure')

```{r echo = FALSE, warnings=FALSE, message=FALSE, results = "asis"}

# Summary of results and image file names that will be references in text
results <- df %>% 
  group_by(strata) %>% 
  dplyr::summarise_each(funs(mean)) %>% 
  mutate(fig1 = paste0("fig1_", strata),
         fig2 = paste0("fig2_", strata))

#Text template (each strata will have its own section)
template <- "# The %s stratum
The mean of *x* in %s stratum was %1.1f. Relationships between *x* and *y* and *x* and *z* can be found in `r figr('%s', TRUE, type='Figure')` and `r figr('%s', TRUE, type='Figure')`.

"

#Create markdown sections in for loop
for(i in seq(nrow(results))) {
  current <- results[i, ]
  cat(sprintf(template, 
              current$strata, current$strata, 
              current$x, 
              current$fig1, current$fig2))
}

#Also doesn't work:
template <- "# The %s stratum
The mean in %s stratum was %1.0f. Results can be found in "
template2 <- " and "
template3 <- ".

"

`figr('%s', TRUE, type='Figure')` and `figr('%s', TRUE, type='Figure')`."

#For loop
for(i in seq(nrow(results))) {
  current <- results[i, ]
  cat(sprintf(template,
            current$strata, current$strata,
            current$mean,
            current$fig_1, current$fig_2))
  print(paste0("`r figr(",paste0("'", current$fig1,"'"), TRUE, type='Figure'))
  cat(sprintf(template2))
  print(paste0("`r figr(",paste0("'", current$fig2,"'"), "TRUE, type='Figure'),`"))
  cat(sprintf(template3))
 }
```

結論部分

報告和圖中的一些討論文本r figr('last_plot',TRUE, type='Figure')

*NOTE:* I don't know how to automate the looped portion of the list of figures here, so I've done it by hand.

```{r 'first_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="The caption for the first figure."}
suppressMessages(print(first_plot))
```

```{r 'fig1_A', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig1_A."}
grid.raster(fig1_A)
```

```{r 'fig2_A', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig2_A."}
grid.raster(fig2_A)
```

```{r 'fig1_B', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig1_B."}
grid.raster(fig1_B)
```

```{r 'fig2_B', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig2_B."}
grid.raster(fig2_B)
```

```{r 'fig1_C', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig1_C."}
grid.raster(fig1_C)
```

```{r 'fig2_C', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig2_C."}
grid.raster(fig2_C)
```

```{r 'last_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="The caption for the last figure."}
suppressMessages(print(last_plot))
```

解決方案

  1. 使用knit_expand()
  2. 使用captioner而不是kfigr
  3. 這會在文本和報告末尾對您的數字(或表格)進行編號。
  4. 此腳本向您展示如何在for循環中創建markdown段落,這些循環具有對圖形的文本引用。
  5. 它還向您展示了如何在保留數字順序的同時在for循環中創建自定義圖形標題。
  6. 如果你展示如何使用brew做#4和#5我會給你所有的SO點。

圖書館

library(knitr) library(dplyr) library(png) library(grid) library(pander) library(ggplot2) library(devtools) library(captioner)

使用captioner包創建一個fig_nums()函數( https://github.com/adletaw/captioner/blob/master/vignettes/using_captioner.Rmd

fig_nums <- captioner(prefix = "Figure")

數據

每年我們都有不同數量的階層,因此需要循環。

df <- rbind(
  data.frame(strata = rep("A", 10), x = rnorm(10, mean= 10), y = rnorm(10, mean = 15), z = rnorm(10, mean = 20)),
  data.frame(strata = rep("B", 10), x = rnorm(10, mean= 5), y = rnorm(10, mean = 10), z = rnorm(10, mean = 15)),
  data.frame(strata = rep("C", 10), x = rnorm(10, mean= 15), y = rnorm(10, mean = 20), z = rnorm(10, mean = 10)))

first_plot:在for循環之前應該出現在列表中的數字按分層創建部分

first_plot <- ggplot(df, aes(x, fill=strata)) + geom_histogram()
fig_nums("first_plot", display = FALSE)

last_plot:在for循環之后應該出現在列表中的數字按層次創建部分

last_plot <- ggplot(df, aes(x = strata, y = z)) + geom_boxplot()

圖生成

一旦你想要了解你想要的東西,請評論這一部分。 如果你在R中進行大量的映射,這一步不會感到復雜,不自然,次優,不必要,或者像一個非常糟糕的主意。

strat <- unique(df$strata)

  for (i in seq_along(strat)) {
   sub <- df %>% filter(strata %in% strat[i])
   fig1 <- ggplot(sub, aes(x = x, y = y)) + geom_point()
   ggsave(fig1, file=paste0("fig1_", strat[i], ".png"))
   fig2 <- ggplot(sub, aes(x = x, y = z)) + geom_point() 
   ggsave(fig2, file=paste0("fig2_", strat[i], ".png"))
 }        

加載png

df_figs <- list.files(pattern = "\\.png$")
for (i in df_figs){  
   name <- gsub("-",".",i)
   name <- gsub(".png","",name)  
   i <- paste(".\\",i,sep="")
   assign(name,readPNG(i))
}

介紹

報告中的一些介紹性文字和圖r fig_nums("first_plot", display="cite")

將在文本中引用的結果和圖像文件名:

```{r echo = FALSE, warnings=FALSE, message=FALSE, results = "asis"}

    results <- df %>% 
      group_by(strata) %>% 
      dplyr::summarise_each(funs(mean)) %>% 
      mutate(fig1 = paste0("fig1_", strata),
             fig2 = paste0("fig2_", strata))

```

```{r run-numeric-md, warning=FALSE, include=FALSE}

#The text for the markdown sections in for loop... the knit_expand() is the work-horse here.

out = NULL
for (i in as.character(unique(results$strata))) {
  out = c(out, knit_expand(text=c('#### The *{{i}}* strata',
                                  '\n',
                                  'The mean of *x* is ',
                                  '{{paste(sprintf("%1.1f", results$x[results$strata==i]))}}', '({{fig_nums(results$fig1[results$strata==i],display="cite")}}).',
                                  '\n'
  )))
}

```

為每個階層創建部分

`r paste(knit(text = out), collapse = '\n')`

結論

報告中的一些討論文本和圖r fig_nums("last_plot",display="cite")

數字清單

`r fig_nums("first_plot",caption="Here is the caption for the first figure.")`

```{r 'first_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6}
suppressMessages(print(first_plot))
```

```{r figcaps, include=FALSE}
caps = NULL

for (i in as.character(unique(results$strata))) {
  caps = c(caps, knit_expand(  
    text=c({{fig_nums(results$fig1[results$strata==i], caption="Caption text for strata *{{i}}* goes here.")}},
           '``` {r {{results$fig1[results$strata==i]}}, echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6}',
           {{paste0('grid.raster(',results$fig1[results$strata==i],')')}},
                                    '```',
           '\n')))
}

#DON'T FORGET TO UNLIST!
src <- unlist(caps)
```

`r paste(knit(text = src),sep='\n')`

`r fig_nums("last_plot", caption="The caption for the last figure.")`

```{r 'last_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6}
suppressMessages(print(last_plot))
```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM