plotly.R
plotly.R copied to clipboard
Define fig size with subplot while height is deprecated in layout
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 thelayout
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)
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.
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
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)