r - 在同一块中使用 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")
```
解决方案
使用此处的评论解决。
打印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)
}
```
推荐阅读
- javascript - 无法理解为什么它给了我:未捕获(承诺)类型错误:无法读取未定义的属性“blabla”
- ruby-on-rails - 使用 Rails API 创建和发送电子邮件附件的最佳实践是什么
- python - Shutil.move 不移动文件夹,而是移动文件夹的内容
- python - 使用字符串和 NaN 提取多索引 pandas 数据帧的最大值
- python - 如何使用 tf.data.Dataset.map 对两个 tf.data.Datasets 进行元素总和,两者都无限迭代?
- android - Room database with Kotlin inline class as an Entity field
- javascript - Bootstrap Carousel 堆叠图像
- javascript - 使用小书签创建弹出菜单
- python - 根据其他列中的值平均某些列
- jquery - rangeslider.js 为范围设置默认最小值,最大值