RMarkdown 编织产生每个图两次

RMarkdown knitting produces each plot twice

这是代码:

---
title: "Data Analysis"
author: "Author"
date: "`r Sys.Date()`"
output: word_document
---

{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

library(viridisLite)
library(ggplot2)
library(GGally)
library(plotly)
library(readxl)
library(vtable)
library(imputeTS)
library(janitor)
library(tibble)
library(readr)
library(survival)
library(survminer)
library(tidyr)
library(tidyverse)
library(broom)
library(DataExplorer)
library(dplyr)
library(WeibullR)
library(ggfortify)
library(factoextra)
library(gridExtra)
```

Text Text Text

{r unsorted, echo=FALSE, warning=FALSE}
setwd("C:/Users/R//")
df = data.frame(read.csv("file.csv"
                         , header = TRUE
                         , sep = ";"
                         , dec = ","
                         , na.strings = "---"))

# clean data frame ----
df<- df %>%
  clean_names()
df<- df %>% janitor::remove_empty(whic=c("rows"))
df<- df %>% janitor::remove_empty(whic=c("cols"))
df<- dplyr::distinct(df)
colnames(df)[1]<- "country"
df_unsorted<- df

DataExplorer::plot_missing(df_unsorted[, 1:ncol(df_unsorted)]
            , theme_config =list(axis.text=element_text(size = 12))) + theme_bw()

```

无论如何,这会导致:

很奇怪,这些图看起来略有不同,但我看不出绘制它们的任何原因,分别是为什么其中一个。 我也看过 Why is this graph showing up twice in R Markdown? 但没有给出答案。

问题是,作为副作用,DataExplorer::plot_missing 会打印情节,returns 会隐藏 ggplot 对象。通过 + theme_bw 调整返回的 ggplot 对象的 theme 你会得到第二个图。

防止这种情况发生的一种方法是通过 ggtheme 参数设置主题。

使用 ?DataExplorer::plot_missing 中的默认示例:

---
output: html_document
date: '2022-04-20'
---

```{r}
library(DataExplorer)
library(ggplot2)

plot_missing(airquality, theme_config = list(axis.text = element_text(size = 12)), ggtheme = theme_bw())
```