How to make flot responsive?
Asked Answered
H

5

13

In the following fiddle:

http://jsfiddle.net/jamitzky/9x7aJ/

How can I make the graph's width change if the window width changes?

code:

$(function () {
var d1 = [];
for (var i = 0; i < 14; i += 0.5)
    d1.push([i, Math.sin(i)]);

var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];

// a null signifies separate line segments
var d3 = [[0, 12], [7, 12], null, [7, 2.5], [12, 2.5]];

$.plot($("#placeholder"), [ d1, d2, d3 ]);
});
Haslam answered 21/6, 2013 at 19:24 Comment(1)
Do you need Flot to be responsive to the window size when opened or to resize with the window?Bedroll
B
22

Try something like this:

Flot will auto draw to the container it's in. So if your div is responsive Flot will be responsive.

http://jsfiddle.net/9x7aJ/2029/

then all you have to do is redraw the flot if your window resizes:

You can watch to see if the window resizes with:

    window.onresize = function(event) {
    ...
}

(see: JavaScript window resize event)

Bedroll answered 21/6, 2013 at 19:36 Comment(1)
This works great but in my case you also need to clean the chart everytime. Example code window.onresize = function(event) { plot2.destroy(); //and then plot2 = $.jqplot........}Immaterial
L
22

Also there's a official flot resize plugin

http://people.iola.dk/olau/flot/examples/resize.html

Lapel answered 24/2, 2014 at 11:44 Comment(2)
This seems like the much simpler, native solution. I tried to do it manually, similar to the accepted answer, but I had issues presumably because my flot chart was in an angular directive. Using the resize plugin fixed all my issues instantly.Gamelan
would definitely also recommend upgrading to the latest flot (0.8.3 as of writing), it has some excellent IE8 error fixes, which i had to previously monkey patch the official flot with try-catchingLapel
C
1

Just include jquery.flot.resize.min.js script from https://github.com/flot/flot in your page. It will become responsive.

Coroneted answered 6/12, 2016 at 4:48 Comment(0)
H
1

I had the same problem and the solution was:

<script language="javascript" type="text/javascript" src="http://people.iola.dk/olau/flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="http://people.iola.dk/olau/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="http://people.iola.dk/olau/flot/jquery.flot.resize.js"></script>
<script src="./jquery.flot.axislabels.js"></script>
Handcar answered 3/5, 2017 at 4:23 Comment(0)
F
0

Just use some css. Any modern browser can use (inline, stylesheet):

<div id="chart" style="width: 100%!important"></div>
Fils answered 14/10, 2017 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.