Why does ggbreak output an extra empty plot (RMarkdown)?

59 Views Asked by At

I am plotting a barchart with uneven frequencies, so that I make use of the ggbreak package. It works, but in my RMarkdown file, it outputs an empty plot in addition to the desired plot. When knitting, the extra empty plot is gone, however.

MWE:

library(ggplot2)
library(ggbreak)

set.seed(1)
fruit <- sample(c("Apple","Banana","Pear","Plum","Dragonfruit"),
     100,replace = TRUE,prob = c(.5,.1,.1,.1,.1))
df <- as.data.frame(table(fruit))

ggplot(df,aes(x=fruit,y=Freq)) +
  geom_col() +
  scale_y_break(c(20,50)) +
  coord_flip()  

Here is the output:

screenshot showing the output of R Markdown with one extra empty plot

As you can see, it outputs the correct plot (aside from the x-axis scale issue at the higher end). As soon as I comment out the scale_y_break command, the extra plot disappears, which is why I believe ggbreak is causing it. I can't find any info on this, besides limitations of export, which I don't use.

What causes this behaviour, and what can I do to troubleshoot it? I often use RMarkdown for live demonstrations, and I would like the output to be clean.

A similar problem is asked in this question: ggarrange with common legend produces extra blank plot in markdown . The answers did not help me.

The pdf-null answer does 1. not explain what it does, and why it is a work-around and 2. does not work in my case. The other answer saving the plot and then adding the "problematic" code, doesn't work either, see below.

What I have tried:

p <- ggplot(df,aes(x=fruit,y=Freq))+
  geom_col()+
  scale_y_break(c(20,50))+
  coord_flip()
p

and

p <- ggplot(df,aes(x=fruit,y=Freq))+
  geom_col()+
  coord_flip()
p + scale_y_break(c(20,50))
0

There are 0 best solutions below