R: how do you embed plots into a tab in RMarkdown in a procedural fashion?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-10 05:20:06

问题


I can embed plots using just RMarkdown's {.tabset}

#### Heading  {.tabset}
##### Subheading 1
```{r, echo=F}
df[[1]]    
```

This produces individual tabs with the specified graphs (df is a list of graphs, calling df[[i]] produces a graph) in the preview pane (renders all the graphs inline in RStudio).


And I can generate just the tabs using a for loop.

```{r, results='asis', echo = FALSE}
for (i in 1:length(gg0)) {
  cat("##### ",q$Subheading[i],"\n")
}
```

And this produces the desired output - the tabs with the names in the Subheading column.


However, I am stuck in trying to generate the graphs themselves using the for loop similar to how I did when I coded it manually.

Extending the above, I tried to generate the markdown that produced the initial output but the plot fails to generate (both in the inline markdown and preview).

```{r, results='asis', echo = FALSE}
for (i in 1:length(gg0)) {
  cat("##### ",q$Subheading[i],"\n")
    cat('```{r, echo=F} \n')
    cat("gg0[[",i,"]]\n")
    cat('``` \n')
}
```

Maybe I am missing a finer point regarding markdown? I have tried various patterns using cat (and even without)

I would prefer a RMarkdown solution but other solutions are just as welcome.


回答1:


I played around a little and found a solution. You have to use print within the asis code chunk...

```{r}
library(ggplot2)
gg0 <- list()
gg0[[1]] <- ggplot(mtcars, aes(mpg, hp)) + geom_point()
gg0[[2]] <- ggplot(mtcars, aes(mpg, disp)) + geom_point()
gg0[[3]] <- ggplot(mtcars, aes(mpg, drat)) + geom_point()

headings <- c('hp','disp','drat')
```

#### Heading  {.tabset}
```{r, results='asis', echo = FALSE}
for (i in 1:length(gg0)) {
  cat("##### ",headings[i],"\n")
  print(gg0[[i]])
  cat('\n\n')
}
```

As an explanation, the cat command together with results='asis' produces the markdown code for a lower level headline and prints the ggplot graph afterwards. Since we used `{.tabset} in the parent headline, it creates the plots in separate tabs.




回答2:


Adding both plot.new(), dev.off() inside the for loop solves the problem of adding all the figures in the last tab. See the complete solution here.



来源:https://stackoverflow.com/questions/43636120/r-how-do-you-embed-plots-into-a-tab-in-rmarkdown-in-a-procedural-fashion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!