Ggplot graphs appear out of order in R Notebook and its html rendering

ggplot2

#1

Figures plotted by ggplot in an R Notebook appear out of order both in the notebook and in the .html file that is rendered when the document is saved. Here is a simple example:

library(tidyverse)
d <- data.frame(v = c("A", "B", "C"), vl = rnorm(99, 0, 1))

summaries <- d %>%
  group_by(v) %>%
  summarize(n=n(),
            summary=list(as_tibble(as.list(summary(vl)))))%>%
  unnest()
print(summaries)
for (var in sort(unique(d$v))) {
  print(d %>% filter(v==var) %>%
          ggplot(aes(vl)) +
          geom_histogram(bins=30) +
          ggtitle(var)
  )
  print(d %>% filter(v==var) %>%
          ggplot(aes(v, vl)) +
          geom_violin() +
          ggtitle(paste("Violin plot of", var))
  )
}
print(d %>%
        ggplot(aes(vl, color=v)) +
        stat_ecdf(aes(linetype = v)) +
        ggtitle("CDFs")
)

When I run this, the table appears first, and the seven graphs appear in the order: C, Violin plot of B, A, B, Violin plot of A, Violin plot of C, CDFs. Obviously, that is not the order in which they were generated by the for loop.

There was a discussion of a similar problem in 2017 on the old RStudio community site, where someone from the company said it was being fixed, but apparently not (yet). Help would be welcome. Thank you.

I am running RStudio Version 1.1.456 on Mac OSX (10.13.6), R version 3.4.3 (2017-11-30).


#2

If you want to keep up with the issue, it’s being tracked here:


#3

Thank you for the pointer.