【问题标题】:Overlapping marginal histograms using ggExtra in the same chunk在同一块中使用 ggExtra 重叠边缘直方图
【发布时间】: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


    【解决方案1】:

    使用评论here解决。

    打印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)
    }
    ```
    

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 1970-01-01
      • 2013-07-23
      • 2021-10-12
      • 2012-07-15
      • 1970-01-01
      • 2021-10-31
      • 2015-11-24
      • 2014-09-18
      相关资源
      最近更新 更多