【发布时间】:2021-01-02 16:38:40
【问题描述】:
我正在尝试使用 for 循环创建带有边缘直方图的散点图。下面是我的 Rmarkdown 文件和输出。输出应该显示三个不同的散点图,但它只显示一个。我相信当它们在同一个块中时,它们会放在彼此之上。
我不想在循环中创建块。如何使用循环创建三个散点图?
---
title: "My Report"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(ggExtra)
library(tidyverse)
```
## In for-loop
```{r}
for (i in 1:3) {
df <- data.frame(x = rnorm(50), y = rnorm(50))
p <- ggplot(df, aes(x = x, y = y)) +
geom_point()
print(ggExtra::ggMarginal(p, type = "histogram"))
}
```
## No for-loop
```{r}
df <- data.frame(x = rnorm(50), y = rnorm(50))
p <- ggplot(df, aes(x = x, y = y)) +
geom_point()
ggExtra::ggMarginal(p, type = "histogram")
df <- data.frame(x = rnorm(50), y = rnorm(50))
p <- ggplot(df, aes(x = x, y = y)) +
geom_point()
ggExtra::ggMarginal(p, type = "histogram")
```
## Separate Chunks
```{r}
df <- data.frame(x = rnorm(50), y = rnorm(50))
p <- ggplot(df, aes(x = x, y = y)) +
geom_point()
ggExtra::ggMarginal(p, type = "histogram")
```
```{r}
df <- data.frame(x = rnorm(50), y = rnorm(50))
p <- ggplot(df, aes(x = x, y = y)) +
geom_point()
ggExtra::ggMarginal(p, type = "histogram")
```
【问题讨论】:
标签: r ggplot2 r-markdown knitr