About a week ago, I had some responsive plotly.js plots working and now they are not - I’m not sure if I changed something or if plotly.js was updated. I did read the post about including the d3 var explicitly, which I’ve now added to my app. However, it’s still not responsive.
Here’s the relevant code (assume data and layout are filled in):
The graphs show successfully and the Javascript console shows no runtime errors - it’s strictly the resizing where nothing occurs. I suspect it’s something with the last line of code (specifically, Plotly.Plots.resize()). I also tried using the recent solution of relayout to no avail (after wrapping it on a window.onresize function). You can view the full source code here.
Any help would be hugely appreciated. Thanks a lot.
Your code is not missing anything, but rather has too many conflicting things.
Setting window.resize multiple times does not add as many on-resize handlers, but instead it overrides them, keeping only the last handler set active. In your case the last window.onresize statement resizes the blue line graph, which does behave responsively as intended.
To add multiple handlers to the same event, you’ll have to use to addEventListener method instead. For example,
window.addEventListener('resize', function() { Plotly.Plots.resize('blue_line'); });
window.addEventListener('resize', function() { Plotly.Plots.resize('red_line'); });
// ... and so on
Etienne, thank you so much, it worked! I hope this post can help someone else from making the same silly mistake in the future. Thank you for helping out so quickly.
In case anyone else needs some clarification on this, you’ll need to use window.addEventListenerinstead of window.onresize. Took me a couple tries to get this working. I was able to get both ‘resize’ and ‘relayout’ working within the EventListener for multiple plots on a single page.
I finally got this working in react.
I understand this is not totally relevant to plotlyjs but still posting the answer here.
This is quite to difficult to figure out for someone relatively new to javascript. Hopefully, it will save someone else a lot of time. This is what worked for me.
So, what’s a bottom line? Is it responsive? What if I dont want to specify a percentage of the parent? I just want my chart taking all available space any time I resize.
Thanks kausti, your solution got me on the right track.
For React in 2020, we can use React.CreateRef() instead of looking up the dom element by ID. We don’t have to import PlotlyCore or call PlotlyCore.relayout at all.