daattali/ggExtra

plots don't print in-line in R Notebooks

Aariq opened this issue · 7 comments

Aariq commented

ggMarginal() plots don't print in-line or in the Viewer tab (i.e. they don't print at all) in R Notebooks.
ggExtra notebook bug.Rmd.zip

Hey @Aariq , a few notes:

  • In order to view the ggMarginal plot inline in an R Notebook, you need to follow the example given in #89 (comment). Try changing your example to the following 2 chunk alternative:
---
title: "R Notebook"
output: html_notebook
---
```{r}
library(ggplot2)
library(ggExtra)

p <- ggplot(trees, aes(x = Height, y = Girth)) + geom_point() +
  geom_smooth(method = "lm")

p_marg <- ggMarginal(p, type = "histogram")
library(grid)
grid.newpage()
grid.draw(p_marg)
  • R Notebooks behave a bit differently than normal R Markdown documents when it comes to the preview feature. According to RStudio:

The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.

...so if you want to see your ggMarginal plot in a preview, you have to run the code chunks responsible for creating the plot first.

Aariq commented

Thanks! Sorry I didn't find #89 before posting this. Is there a reason why grid.draw() isn't the default print method? It would be nice if this just "worked", if you know what I mean.

It actually is:

ggExtra/R/ggMarginal.R

Lines 191 to 194 in 4468f21

print.ggExtraPlot <- function(x, newpage = grDevices::dev.interactive(), ...) {
if (newpage) grid::grid.newpage()
grid::grid.draw(x)
}

I didn't keep up with #89 so I'm not sure why ggMarginal needs to use the 2-chunk approach to printing in notebooks/Rmarkdown docs.

I'm still not sure why notebooks/rmd behave this way, and whether or not this is a big. If you follow the links in #89 you'll see this is not a resolved question. This information is also available in the README (which is, admittedly, a bit long). If you solved the problem (even though we don't know the root of the issue), you can close the issue

Aariq commented

I don't really know what the code does here, but this change makes it work inline:

print.ggExtraPlot <- function(x, newpage = is.null(vp), vp = NULL,...) {
  if (newpage) grid::grid.newpage()
  grid::grid.draw(x)
}

I kind of just haphazardly copied things from print.ggplot() until I found something that works. Happy to submit a PR if this doesn't break things. I don't know what newpage = grDevices::def.interactive() was doing.

Hey @Aariq , thanks for attempting to fix...Unfortunately your fix would re-introduce the problem fixed in #48, so I'm thinking we leave things as is for now.

Aariq commented

Got it.