plotly.R icon indicating copy to clipboard operation
plotly.R copied to clipboard

Define fig size with subplot while height is deprecated in layout

Open rfenouil opened this issue 5 years ago • 3 comments

When using height argument in layout, I have a warning telling that this argument is deprecated. I can use height in plot_ly function directly which is very fine.

However, when using subplot, I did not find a convenient way to specify the total height for the assembled panels. Should subplot accept its own height and width arguments ?

If I understand correctly, subplot uses by default the layout from one of the contained plots. It seems to be the case for width and height but I find it confusing because:

  • height is encouraged to be defined outside of the layout function
  • it seems counterintuitive that the size of the panels assembly is controled by the size defined in one subpanel
panel1 = plot_ly(x = 1, y = rnorm(100), height = 600, width = 100) %>% 
           add_trace(type = "violin")
panel2 = plot_ly(x = 1, y = rnorm(100), height = 300, width = 300) %>% 
           add_trace(type = "violin")

# Size of individual panels are respected
panel1
panel2

# Total figure size uses size of one subpanel (one can use 'which_layout' to control which)
subplot(panel1, panel2)
subplot(panel2, panel1)

rfenouil avatar Sep 05 '19 13:09 rfenouil

I just run into this issue. I don't see how one can set size of a subplot directly, and setting it inside the last subplot is rather inconvenient to say the least.

giordano avatar Feb 04 '20 12:02 giordano

I tried getting around this issue by passing to each subplot the individual plotheight multiplied with the number of subplots (nrows) so the total height of the total figure would be plotheight * nrows. Then in theory it shouldn't matter which layout is used, however in practice it turns out the heights aren't strictly adhered too (for mysterious reasons to me). Comparing the total height of the first two panels you can clearly see the x axes are at different heights.

update: I opened an issue about this and found a hacky workaround

subplot height mismatch

generate_subplot <- function(nrows, margin = NULL){

  if(is.null(margin)) margin = c(0,0,0,0)

  p <- plotly::plot_ly(mtcars, 
    x = ~cyl, y = ~mpg, 
    color = ~rownames(.data), 
    type = "bar",
    height = 150 * nrows
  ) %>% plotly::layout(
    showlegend = FALSE,
    shapes = list(
      list(
        type = 'rect',
        fillcolor = "gray", 
        line = list(color = "gray"), 
        opacity = 0.05,
        x0 = 0, x1 = 1,
        y0 = 0, y1 = 1,
        xref = 'paper',
        yref = 'paper'
      )
    )
  )
  
  plotly::subplot(
    rep_len(list(p), nrows),
    nrows = nrows,
    margin = margin
  )

}

generate_subplot(2)
generate_subplot(4)
generate_subplot(8)

nlooije avatar Jun 13 '22 12:06 nlooije