Home > OS >  Several ggplots plots with different heights and widths wrapped in function
Several ggplots plots with different heights and widths wrapped in function

Time:06-22

Apologies, this is not a fully reproducible example but should hopefully convey the gist of my problem using the current approach. I (try to) use the following code in a Jupyter notebook to print several graphs with different sizes:

#reporducible data
temp <- mtcars[, 1:3]
colnames(temp) <- c("x1", "z", "y1")

plotting_function <- function(data_to_vis) {
  
  options(repr.plot.width = 5, repr.plot.height = 5) 
  p1 <- ggplot(data_to_vis, aes(x=x1, y=y1))  
    geom_point(size = 3)         
  print(p1)
  
  options(repr.plot.width = 20, repr.plot.height = 20) 
  p2 <- ggplot(data_to_vis, aes(x=x1, y=y1))  
    geom_point()  
    facet_wrap(~z)  
    theme(aspect.ratio = 1)
  print(p2)
}

library(ggplot2)
plotting_function(temp)

Using:

options(repr.plot.width = 5, repr.plot.height = 5) 

usually works fine but not in this use case - it is not adhered to - the first graph p1 is printed using:

options(repr.plot.width = 20, repr.plot.height = 20) 

Maybe there is a better approach for this use case?

CodePudding user response:

I don't use Jupyter, so I experimented with https://jupyter.org/try to come up with this "solution". I can't explain it, but to me it certainly looks like a bug.

The problem is that options() settings aren't handled in the expected order. The options you set apply to the previous plot. So this simple change to your script worked for me:

temp <- mtcars[, 1:3]
colnames(temp) <- c("x1", "z", "y1")

plotting_function <- function(data_to_vis) {
  
  p1 <- ggplot(data_to_vis, aes(x=x1, y=y1))  
    geom_point(size = 3)         
  print(p1)
  options(repr.plot.width = 5, repr.plot.height = 5) 

  p2 <- ggplot(data_to_vis, aes(x=x1, y=y1))  
    geom_point()  
    facet_wrap(~z)  
    theme(aspect.ratio = 1)
  print(p2)
  options(repr.plot.width = 20, repr.plot.height = 20) 
  
}

library(ggplot2)
plotting_function(temp)

You can also move the first options() setting before printing p1, but you can't move the second one before printing p2, or it will also apply to p1.

Bug? Looks like it to me.

  • Related