Ben
Ben

Reputation: 1522

RMarkdown knitting produces each plot twice

This is the code:

---
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()

```

which, whyever, results in:

img

weird enough, that the plots look slightly different but I don't see any reasons why they are plotted, respectively why one of them. I've also seen Why is this graph showing up twice in R Markdown? but there is no answer given.

Upvotes: 1

Views: 522

Answers (1)

stefan
stefan

Reputation: 123783

The issue is that as a side effect DataExplorer::plot_missing prints the plot and returns the ggplot object invisibly. By adjusting the theme of the returned ggplot object via + theme_bw you get a second plot.

One option to prevent that would be to set the theme via the ggtheme argument.

Making use of the default example from ?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())
```

enter image description here

Upvotes: 3

Related Questions