Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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],"
")
}
```

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],"
")
    cat('```{r, echo=F} 
')
    cat("gg0[[",i,"]]
")
    cat('``` 
')
}
```

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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],"
")
  print(gg0[[i]])
  cat('

')
}
```

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...