首页 > 解决方案 > 在同一块中使用 ggExtra 重叠边缘直方图

问题描述

我正在尝试使用 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")
```

在此处输入图像描述 在此处输入图像描述

标签: rggplot2r-markdownknitr

解决方案


使用此处的评论解决。

打印ggmarginal对象时,请使用print(p, newpage = TRUE)而不是print(p).

```{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"), newpage = TRUE)
}
```

推荐阅读