Add analytics
[bus.git] / busui / owa / modules / base / js / includes / jquery / flot / API.txt
maxious 1 Flot Reference
2 --------------
3
4 Consider a call to the plot function:
5
6 var plot = $.plot(placeholder, data, options)
7
8 The placeholder is a jQuery object or DOM element or jQuery expression
9 that the plot will be put into. This placeholder needs to have its
10 width and height set as explained in the README (go read that now if
11 you haven't, it's short). The plot will modify some properties of the
12 placeholder so it's recommended you simply pass in a div that you
13 don't use for anything else. Make sure you check any fancy styling
14 you apply to the div, e.g. background images have been reported to be a
15 problem on IE 7.
16
17 The format of the data is documented below, as is the available
18 options. The "plot" object returned has some methods you can call.
19 These are documented separately below.
20
21 Note that in general Flot gives no guarantees if you change any of the
22 objects you pass in to the plot function or get out of it since
23 they're not necessarily deep-copied.
24
25
26 Data Format
27 -----------
28
29 The data is an array of data series:
30
31 [ series1, series2, ... ]
32
33 A series can either be raw data or an object with properties. The raw
34 data format is an array of points:
35
36 [ [x1, y1], [x2, y2], ... ]
37
38 E.g.
39
40 [ [1, 3], [2, 14.01], [3.5, 3.14] ]
41
42 Note that to simplify the internal logic in Flot both the x and y
43 values must be numbers (even if specifying time series, see below for
44 how to do this). This is a common problem because you might retrieve
45 data from the database and serialize them directly to JSON without
46 noticing the wrong type. If you're getting mysterious errors, double
47 check that you're inputting numbers and not strings.
48
49 If a null is specified as a point or if one of the coordinates is null
50 or couldn't be converted to a number, the point is ignored when
51 drawing. As a special case, a null value for lines is interpreted as a
52 line segment end, i.e. the points before and after the null value are
53 not connected.
54
55 Lines and points take two coordinates. For bars, you can specify a
56 third coordinate which is the bottom of the bar (defaults to 0).
57
58 The format of a single series object is as follows:
59
60 {
61 color: color or number
62 data: rawdata
63 label: string
64 lines: specific lines options
65 bars: specific bars options
66 points: specific points options
67 xaxis: 1 or 2
68 yaxis: 1 or 2
69 clickable: boolean
70 hoverable: boolean
71 shadowSize: number
72 }
73
74 You don't have to specify any of them except the data, the rest are
75 options that will get default values. Typically you'd only specify
76 label and data, like this:
77
78 {
79 label: "y = 3",
80 data: [[0, 3], [10, 3]]
81 }
82
83 The label is used for the legend, if you don't specify one, the series
84 will not show up in the legend.
85
86 If you don't specify color, the series will get a color from the
87 auto-generated colors. The color is either a CSS color specification
88 (like "rgb(255, 100, 123)") or an integer that specifies which of
89 auto-generated colors to select, e.g. 0 will get color no. 0, etc.
90
91 The latter is mostly useful if you let the user add and remove series,
92 in which case you can hard-code the color index to prevent the colors
93 from jumping around between the series.
94
95 The "xaxis" and "yaxis" options specify which axis to use, specify 2
96 to get the secondary axis (x axis at top or y axis to the right).
97 E.g., you can use this to make a dual axis plot by specifying
98 { yaxis: 2 } for one data series.
99
100 "clickable" and "hoverable" can be set to false to disable
101 interactivity for specific series if interactivity is turned on in
102 the plot, see below.
103
104 The rest of the options are all documented below as they are the same
105 as the default options passed in via the options parameter in the plot
106 commmand. When you specify them for a specific data series, they will
107 override the default options for the plot for that data series.
108
109 Here's a complete example of a simple data specification:
110
111 [ { label: "Foo", data: [ [10, 1], [17, -14], [30, 5] ] },
112 { label: "Bar", data: [ [11, 13], [19, 11], [30, -7] ] } ]
113
114
115 Plot Options
116 ------------
117
118 All options are completely optional. They are documented individually
119 below, to change them you just specify them in an object, e.g.
120
121 var options = {
122 series: {
123 lines: { show: true },
124 points: { show: true }
125 }
126 };
127
128 $.plot(placeholder, data, options);
129
130
131 Customizing the legend
132 ======================
133
134 legend: {
135 show: boolean
136 labelFormatter: null or (fn: string, series object -> string)
137 labelBoxBorderColor: color
138 noColumns: number
139 position: "ne" or "nw" or "se" or "sw"
140 margin: number of pixels or [x margin, y margin]
141 backgroundColor: null or color
142 backgroundOpacity: number between 0 and 1
143 container: null or jQuery object/DOM element/jQuery expression
144 }
145
146 The legend is generated as a table with the data series labels and
147 small label boxes with the color of the series. If you want to format
148 the labels in some way, e.g. make them to links, you can pass in a
149 function for "labelFormatter". Here's an example that makes them
150 clickable:
151
152 labelFormatter: function(label, series) {
153 // series is the series object for the label
154 return '<a href="#' + label + '">' + label + '</a>';
155 }
156
157 "noColumns" is the number of columns to divide the legend table into.
158 "position" specifies the overall placement of the legend within the
159 plot (top-right, top-left, etc.) and margin the distance to the plot
160 edge (this can be either a number or an array of two numbers like [x,
161 y]). "backgroundColor" and "backgroundOpacity" specifies the
162 background. The default is a partly transparent auto-detected
163 background.
164
165 If you want the legend to appear somewhere else in the DOM, you can
166 specify "container" as a jQuery object/expression to put the legend
167 table into. The "position" and "margin" etc. options will then be
168 ignored. Note that Flot will overwrite the contents of the container.
169
170
171 Customizing the axes
172 ====================
173
174 xaxis, yaxis, x2axis, y2axis: {
175 mode: null or "time"
176 min: null or number
177 max: null or number
178 autoscaleMargin: null or number
179
180 labelWidth: null or number
181 labelHeight: null or number
182
183 transform: null or fn: number -> number
184 inverseTransform: null or fn: number -> number
185
186 ticks: null or number or ticks array or (fn: range -> ticks array)
187 tickSize: number or array
188 minTickSize: number or array
189 tickFormatter: (fn: number, object -> string) or string
190 tickDecimals: null or number
191 }
192
193 All axes have the same kind of options. The "mode" option
194 determines how the data is interpreted, the default of null means as
195 decimal numbers. Use "time" for time series data, see the next section.
196
197 The options "min"/"max" are the precise minimum/maximum value on the
198 scale. If you don't specify either of them, a value will automatically
199 be chosen based on the minimum/maximum data values.
200
201 The "autoscaleMargin" is a bit esoteric: it's the fraction of margin
202 that the scaling algorithm will add to avoid that the outermost points
203 ends up on the grid border. Note that this margin is only applied
204 when a min or max value is not explicitly set. If a margin is
205 specified, the plot will furthermore extend the axis end-point to the
206 nearest whole tick. The default value is "null" for the x axis and
207 0.02 for the y axis which seems appropriate for most cases.
208
209 "labelWidth" and "labelHeight" specifies a fixed size of the tick
210 labels in pixels. They're useful in case you need to align several
211 plots.
212
213 "transform" and "inverseTransform" are callbacks you can put in to
214 change the way the data is drawn. You can design a function to
215 compress or expand certain parts of the axis non-linearly, e.g.
216 suppress weekends or compress far away points with a logarithm or some
217 other means. When Flot draws the plot, each value is first put through
218 the transform function. Here's an example, the x axis can be turned
219 into a natural logarithm axis with the following code:
220
221 xaxis: {
222 transform: function (v) { return Math.log(v); },
223 inverseTransform: function (v) { return Math.exp(v); }
224 }
225
226 Note that for finding extrema, Flot assumes that the transform
227 function does not reorder values (monotonicity is assumed).
228
229 The inverseTransform is simply the inverse of the transform function
230 (so v == inverseTransform(transform(v)) for all relevant v). It is
231 required for converting from canvas coordinates to data coordinates,
232 e.g. for a mouse interaction where a certain pixel is clicked. If you
233 don't use any interactive features of Flot, you may not need it.
234
235
236 The rest of the options deal with the ticks.
237
238 If you don't specify any ticks, a tick generator algorithm will make
239 some for you. The algorithm has two passes. It first estimates how
240 many ticks would be reasonable and uses this number to compute a nice
241 round tick interval size. Then it generates the ticks.
242
243 You can specify how many ticks the algorithm aims for by setting
244 "ticks" to a number. The algorithm always tries to generate reasonably
245 round tick values so even if you ask for three ticks, you might get
246 five if that fits better with the rounding. If you don't want any
247 ticks at all, set "ticks" to 0 or an empty array.
248
249 Another option is to skip the rounding part and directly set the tick
250 interval size with "tickSize". If you set it to 2, you'll get ticks at
251 2, 4, 6, etc. Alternatively, you can specify that you just don't want
252 ticks at a size less than a specific tick size with "minTickSize".
253 Note that for time series, the format is an array like [2, "month"],
254 see the next section.
255
256 If you want to completely override the tick algorithm, you can specify
257 an array for "ticks", either like this:
258
259 ticks: [0, 1.2, 2.4]
260
261 Or like this where the labels are also customized:
262
263 ticks: [[0, "zero"], [1.2, "one mark"], [2.4, "two marks"]]
264
265 You can mix the two if you like.
266
267 For extra flexibility you can specify a function as the "ticks"
268 parameter. The function will be called with an object with the axis
269 min and max and should return a ticks array. Here's a simplistic tick
270 generator that spits out intervals of pi, suitable for use on the x
271 axis for trigonometric functions:
272
273 function piTickGenerator(axis) {
274 var res = [], i = Math.floor(axis.min / Math.PI);
275 do {
276 var v = i * Math.PI;
277 res.push([v, i + "\u03c0"]);
278 ++i;
279 } while (v < axis.max);
280
281 return res;
282 }
283
284
285 You can control how the ticks look like with "tickDecimals", the
286 number of decimals to display (default is auto-detected).
287
288 Alternatively, for ultimate control over how ticks look like you can
289 provide a function to "tickFormatter". The function is passed two
290 parameters, the tick value and an "axis" object with information, and
291 should return a string. The default formatter looks like this:
292
293 function formatter(val, axis) {
294 return val.toFixed(axis.tickDecimals);
295 }
296
297 The axis object has "min" and "max" with the range of the axis,
298 "tickDecimals" with the number of decimals to round the value to and
299 "tickSize" with the size of the interval between ticks as calculated
300 by the automatic axis scaling algorithm (or specified by you). Here's
301 an example of a custom formatter:
302
303 function suffixFormatter(val, axis) {
304 if (val > 1000000)
305 return (val / 1000000).toFixed(axis.tickDecimals) + " MB";
306 else if (val > 1000)
307 return (val / 1000).toFixed(axis.tickDecimals) + " kB";
308 else
309 return val.toFixed(axis.tickDecimals) + " B";
310 }
311
312 Time series data
313 ================
314
315 Time series are a bit more difficult than scalar data because
316 calendars don't follow a simple base 10 system. For many cases, Flot
317 abstracts most of this away, but it can still be a bit difficult to
318 get the data into Flot. So we'll first discuss the data format.
319
320 The time series support in Flot is based on Javascript timestamps,
321 i.e. everywhere a time value is expected or handed over, a Javascript
322 timestamp number is used. This is a number, not a Date object. A
323 Javascript timestamp is the number of milliseconds since January 1,
324 1970 00:00:00 UTC. This is almost the same as Unix timestamps, except it's
325 in milliseconds, so remember to multiply by 1000!
326
327 You can see a timestamp like this
328
329 alert((new Date()).getTime())
330
331 Normally you want the timestamps to be displayed according to a
332 certain time zone, usually the time zone in which the data has been
333 produced. However, Flot always displays timestamps according to UTC.
334 It has to as the only alternative with core Javascript is to interpret
335 the timestamps according to the time zone that the visitor is in,
336 which means that the ticks will shift unpredictably with the time zone
337 and daylight savings of each visitor.
338
339 So given that there's no good support for custom time zones in
340 Javascript, you'll have to take care of this server-side.
341
342 The easiest way to think about it is to pretend that the data
343 production time zone is UTC, even if it isn't. So if you have a
344 datapoint at 2002-02-20 08:00, you can generate a timestamp for eight
345 o'clock UTC even if it really happened eight o'clock UTC+0200.
346
347 In PHP you can get an appropriate timestamp with
348 'strtotime("2002-02-20 UTC") * 1000', in Python with
349 'calendar.timegm(datetime_object.timetuple()) * 1000', in .NET with
350 something like:
351
352 public static int GetJavascriptTimestamp(System.DateTime input)
353 {
354 System.TimeSpan span = new System.TimeSpan(System.DateTime.Parse("1/1/1970").Ticks);
355 System.DateTime time = input.Subtract(span);
356 return (long)(time.Ticks / 10000);
357 }
358
359 Javascript also has some support for parsing date strings, so it is
360 possible to generate the timestamps manually client-side.
361
362 If you've already got the real UTC timestamp, it's too late to use the
363 pretend trick described above. But you can fix up the timestamps by
364 adding the time zone offset, e.g. for UTC+0200 you would add 2 hours
365 to the UTC timestamp you got. Then it'll look right on the plot. Most
366 programming environments have some means of getting the timezone
367 offset for a specific date (note that you need to get the offset for
368 each individual timestamp to account for daylight savings).
369
370 Once you've gotten the timestamps into the data and specified "time"
371 as the axis mode, Flot will automatically generate relevant ticks and
372 format them. As always, you can tweak the ticks via the "ticks" option
373 - just remember that the values should be timestamps (numbers), not
374 Date objects.
375
376 Tick generation and formatting can also be controlled separately
377 through the following axis options:
378
379 minTickSize: array
380 timeformat: null or format string
381 monthNames: null or array of size 12 of strings
382 twelveHourClock: boolean
383
384 Here "timeformat" is a format string to use. You might use it like
385 this:
386
387 xaxis: {
388 mode: "time"
389 timeformat: "%y/%m/%d"
390 }
391
392 This will result in tick labels like "2000/12/24". The following
393 specifiers are supported
394
395 %h: hours
396 %H: hours (left-padded with a zero)
397 %M: minutes (left-padded with a zero)
398 %S: seconds (left-padded with a zero)
399 %d: day of month (1-31)
400 %m: month (1-12)
401 %y: year (four digits)
402 %b: month name (customizable)
403 %p: am/pm, additionally switches %h/%H to 12 hour instead of 24
404 %P: AM/PM (uppercase version of %p)
405
406 You can customize the month names with the "monthNames" option. For
407 instance, for Danish you might specify:
408
409 monthNames: ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]
410
411 If you set "twelveHourClock" to true, the autogenerated timestamps
412 will use 12 hour AM/PM timestamps instead of 24 hour.
413
414 The format string and month names are used by a very simple built-in
415 format function that takes a date object, a format string (and
416 optionally an array of month names) and returns the formatted string.
417 If needed, you can access it as $.plot.formatDate(date, formatstring,
418 monthNames) or even replace it with another more advanced function
419 from a date library if you're feeling adventurous.
420
421 If everything else fails, you can control the formatting by specifying
422 a custom tick formatter function as usual. Here's a simple example
423 which will format December 24 as 24/12:
424
425 tickFormatter: function (val, axis) {
426 var d = new Date(val);
427 return d.getUTCDate() + "/" + (d.getUTCMonth() + 1);
428 }
429
430 Note that for the time mode "tickSize" and "minTickSize" are a bit
431 special in that they are arrays on the form "[value, unit]" where unit
432 is one of "second", "minute", "hour", "day", "month" and "year". So
433 you can specify
434
435 minTickSize: [1, "month"]
436
437 to get a tick interval size of at least 1 month and correspondingly,
438 if axis.tickSize is [2, "day"] in the tick formatter, the ticks have
439 been produced with two days in-between.
440
441
442
443 Customizing the data series
444 ===========================
445
446 series: {
447 lines, points, bars: {
448 show: boolean
449 lineWidth: number
450 fill: boolean or number
451 fillColor: null or color/gradient
452 }
453
454 points: {
455 radius: number
456 }
457
458 bars: {
459 barWidth: number
460 align: "left" or "center"
461 horizontal: boolean
462 }
463
464 lines: {
465 steps: boolean
466 }
467
468 shadowSize: number
469 }
470
471 colors: [ color1, color2, ... ]
472
473 The options inside "series: {}" are copied to each of the series. So
474 you can specify that all series should have bars by putting it in the
475 global options, or override it for individual series by specifying
476 bars in a particular the series object in the array of data.
477
478 The most important options are "lines", "points" and "bars" that
479 specify whether and how lines, points and bars should be shown for
480 each data series. In case you don't specify anything at all, Flot will
481 default to showing lines (you can turn this off with
482 lines: { show: false}). You can specify the various types
483 independently of each other, and Flot will happily draw each of them
484 in turn (this is probably only useful for lines and points), e.g.
485
486 var options = {
487 series: {
488 lines: { show: true, fill: true, fillColor: "rgba(255, 255, 255, 0.8)" },
489 points: { show: true, fill: false }
490 }
491 };
492
493 "lineWidth" is the thickness of the line or outline in pixels. You can
494 set it to 0 to prevent a line or outline from being drawn; this will
495 also hide the shadow.
496
497 "fill" is whether the shape should be filled. For lines, this produces
498 area graphs. You can use "fillColor" to specify the color of the fill.
499 If "fillColor" evaluates to false (default for everything except
500 points which are filled with white), the fill color is auto-set to the
501 color of the data series. You can adjust the opacity of the fill by
502 setting fill to a number between 0 (fully transparent) and 1 (fully
503 opaque).
504
505 For bars, fillColor can be a gradient, see the gradient documentation
506 below. "barWidth" is the width of the bars in units of the x axis (or
507 the y axis if "horizontal" is true), contrary to most other measures
508 that are specified in pixels. For instance, for time series the unit
509 is milliseconds so 24 * 60 * 60 * 1000 produces bars with the width of
510 a day. "align" specifies whether a bar should be left-aligned
511 (default) or centered on top of the value it represents. When
512 "horizontal" is on, the bars are drawn horizontally, i.e. from the y
513 axis instead of the x axis; note that the bar end points are still
514 defined in the same way so you'll probably want to swap the
515 coordinates if you've been plotting vertical bars first.
516
517 For lines, "steps" specifies whether two adjacent data points are
518 connected with a straight (possibly diagonal) line or with first a
519 horizontal and then a vertical line. Note that this transforms the
520 data by adding extra points.
521
522 "shadowSize" is the default size of shadows in pixels. Set it to 0 to
523 remove shadows.
524
525 The "colors" array specifies a default color theme to get colors for
526 the data series from. You can specify as many colors as you like, like
527 this:
528
529 colors: ["#d18b2c", "#dba255", "#919733"]
530
531 If there are more data series than colors, Flot will try to generate
532 extra colors by lightening and darkening colors in the theme.
533
534
535 Customizing the grid
536 ====================
537
538 grid: {
539 show: boolean
540 aboveData: boolean
541 color: color
542 backgroundColor: color/gradient or null
543 tickColor: color
544 labelMargin: number
545 markings: array of markings or (fn: axes -> array of markings)
546 borderWidth: number
547 borderColor: color or null
548 clickable: boolean
549 hoverable: boolean
550 autoHighlight: boolean
551 mouseActiveRadius: number
552 }
553
554 The grid is the thing with the axes and a number of ticks. "color" is
555 the color of the grid itself whereas "backgroundColor" specifies the
556 background color inside the grid area. The default value of null means
557 that the background is transparent. You can also set a gradient, see
558 the gradient documentation below.
559
560 You can turn off the whole grid including tick labels by setting
561 "show" to false. "aboveData" determines whether the grid is drawn on
562 above the data or below (below is default).
563
564 "tickColor" is the color of the ticks and "labelMargin" is the spacing
565 between tick labels and the grid. Note that you can style the tick
566 labels with CSS, e.g. to change the color. They have class "tickLabel".
567 "borderWidth" is the width of the border around the plot. Set it to 0
568 to disable the border. You can also set "borderColor" if you want the
569 border to have a different color than the grid lines.
570
571 "markings" is used to draw simple lines and rectangular areas in the
572 background of the plot. You can either specify an array of ranges on
573 the form { xaxis: { from, to }, yaxis: { from, to } } (secondary axis
574 coordinates with x2axis/y2axis) or with a function that returns such
575 an array given the axes for the plot in an object as the first
576 parameter.
577
578 You can set the color of markings by specifying "color" in the ranges
579 object. Here's an example array:
580
581 markings: [ { xaxis: { from: 0, to: 2 }, yaxis: { from: 10, to: 10 }, color: "#bb0000" }, ... ]
582
583 If you leave out one of the values, that value is assumed to go to the
584 border of the plot. So for example if you only specify { xaxis: {
585 from: 0, to: 2 } } it means an area that extends from the top to the
586 bottom of the plot in the x range 0-2.
587
588 A line is drawn if from and to are the same, e.g.
589
590 markings: [ { yaxis: { from: 1, to: 1 } }, ... ]
591
592 would draw a line parallel to the x axis at y = 1. You can control the
593 line width with "lineWidth" in the range object.
594
595 An example function might look like this:
596
597 markings: function (axes) {
598 var markings = [];
599 for (var x = Math.floor(axes.xaxis.min); x < axes.xaxis.max; x += 2)
600 markings.push({ xaxis: { from: x, to: x + 1 } });
601 return markings;
602 }
603
604
605 If you set "clickable" to true, the plot will listen for click events
606 on the plot area and fire a "plotclick" event on the placeholder with
607 a position and a nearby data item object as parameters. The coordinates
608 are available both in the unit of the axes (not in pixels) and in
609 global screen coordinates.
610
611 Likewise, if you set "hoverable" to true, the plot will listen for
612 mouse move events on the plot area and fire a "plothover" event with
613 the same parameters as the "plotclick" event. If "autoHighlight" is
614 true (the default), nearby data items are highlighted automatically.
615 If needed, you can disable highlighting and control it yourself with
616 the highlight/unhighlight plot methods described elsewhere.
617
618 You can use "plotclick" and "plothover" events like this:
619
620 $.plot($("#placeholder"), [ d ], { grid: { clickable: true } });
621
622 $("#placeholder").bind("plotclick", function (event, pos, item) {
623 alert("You clicked at " + pos.x + ", " + pos.y);
624 // secondary axis coordinates if present are in pos.x2, pos.y2,
625 // if you need global screen coordinates, they are pos.pageX, pos.pageY
626
627 if (item) {
628 highlight(item.series, item.datapoint);
629 alert("You clicked a point!");
630 }
631 });
632
633 The item object in this example is either null or a nearby object on the form:
634
635 item: {
636 datapoint: the point, e.g. [0, 2]
637 dataIndex: the index of the point in the data array
638 series: the series object
639 seriesIndex: the index of the series
640 pageX, pageY: the global screen coordinates of the point
641 }
642
643 For instance, if you have specified the data like this
644
645 $.plot($("#placeholder"), [ { label: "Foo", data: [[0, 10], [7, 3]] } ], ...);
646
647 and the mouse is near the point (7, 3), "datapoint" is [7, 3],
648 "dataIndex" will be 1, "series" is a normalized series object with
649 among other things the "Foo" label in series.label and the color in
650 series.color, and "seriesIndex" is 0. Note that plugins and options
651 that transform the data can shift the indexes from what you specified
652 in the original data array.
653
654 If you use the above events to update some other information and want
655 to clear out that info in case the mouse goes away, you'll probably
656 also need to listen to "mouseout" events on the placeholder div.
657
658 "mouseActiveRadius" specifies how far the mouse can be from an item
659 and still activate it. If there are two or more points within this
660 radius, Flot chooses the closest item. For bars, the top-most bar
661 (from the latest specified data series) is chosen.
662
663 If you want to disable interactivity for a specific data series, you
664 can set "hoverable" and "clickable" to false in the options for that
665 series, like this { data: [...], label: "Foo", clickable: false }.
666
667
668 Specifying gradients
669 ====================
670
671 A gradient is specified like this:
672
673 { colors: [ color1, color2, ... ] }
674
675 For instance, you might specify a background on the grid going from
676 black to gray like this:
677
678 grid: {
679 backgroundColor: { colors: ["#000", "#999"] }
680 }
681
682 For the series you can specify the gradient as an object that
683 specifies the scaling of the brightness and the opacity of the series
684 color, e.g.
685
686 { colors: [{ opacity: 0.8 }, { brightness: 0.6, opacity: 0.8 } ] }
687
688 where the first color simply has its alpha scaled, whereas the second
689 is also darkened. For instance, for bars the following makes the bars
690 gradually disappear, without outline:
691
692 bars: {
693 show: true,
694 lineWidth: 0,
695 fill: true,
696 fillColor: { colors: [ { opacity: 0.8 }, { opacity: 0.1 } ] }
697 }
698
699 Flot currently only supports vertical gradients drawn from top to
700 bottom because that's what works with IE.
701
702
703 Plot Methods
704 ------------
705
706 The Plot object returned from the plot function has some methods you
707 can call:
708
709 - highlight(series, datapoint)
710
711 Highlight a specific datapoint in the data series. You can either
712 specify the actual objects, e.g. if you got them from a
713 "plotclick" event, or you can specify the indices, e.g.
714 highlight(1, 3) to highlight the fourth point in the second series
715 (remember, zero-based indexing).
716
717
718 - unhighlight(series, datapoint) or unhighlight()
719
720 Remove the highlighting of the point, same parameters as
721 highlight.
722
723 If you call unhighlight with no parameters, e.g. as
724 plot.unhighlight(), all current highlights are removed.
725
726
727 - setData(data)
728
729 You can use this to reset the data used. Note that axis scaling,
730 ticks, legend etc. will not be recomputed (use setupGrid() to do
731 that). You'll probably want to call draw() afterwards.
732
733 You can use this function to speed up redrawing a small plot if
734 you know that the axes won't change. Put in the new data with
735 setData(newdata), call draw(), and you're good to go. Note that
736 for large datasets, almost all the time is consumed in draw()
737 plotting the data so in this case don't bother.
738
739
740 - setupGrid()
741
742 Recalculate and set axis scaling, ticks, legend etc.
743
744 Note that because of the drawing model of the canvas, this
745 function will immediately redraw (actually reinsert in the DOM)
746 the labels and the legend, but not the actual tick lines because
747 they're drawn on the canvas. You need to call draw() to get the
748 canvas redrawn.
749
750 - draw()
751
752 Redraws the plot canvas.
753
754 - triggerRedrawOverlay()
755
756 Schedules an update of an overlay canvas used for drawing
757 interactive things like a selection and point highlights. This
758 is mostly useful for writing plugins. The redraw doesn't happen
759 immediately, instead a timer is set to catch multiple successive
760 redraws (e.g. from a mousemove).
761
762 - width()/height()
763
764 Gets the width and height of the plotting area inside the grid.
765 This is smaller than the canvas or placeholder dimensions as some
766 extra space is needed (e.g. for labels).
767
768 - offset()
769
770 Returns the offset of the plotting area inside the grid relative
771 to the document, useful for instance for calculating mouse
772 positions (event.pageX/Y minus this offset is the pixel position
773 inside the plot).
774
775 - pointOffset({ x: xpos, y: ypos })
776
777 Returns the calculated offset of the data point at (x, y) in data
778 space within the placeholder div. If you are working with dual axes, you
779 can specify the x and y axis references, e.g.
780
781 o = pointOffset({ x: xpos, y: ypos, xaxis: 2, yaxis: 2 })
782 // o.left and o.top now contains the offset within the div
783
784
785 There are also some members that let you peek inside the internal
786 workings of Flot which is useful in some cases. Note that if you change
787 something in the objects returned, you're changing the objects used by
788 Flot to keep track of its state, so be careful.
789
790 - getData()
791
792 Returns an array of the data series currently used in normalized
793 form with missing settings filled in according to the global
794 options. So for instance to find out what color Flot has assigned
795 to the data series, you could do this:
796
797 var series = plot.getData();
798 for (var i = 0; i < series.length; ++i)
799 alert(series[i].color);
800
801 A notable other interesting field besides color is datapoints
802 which has a field "points" with the normalized data points in a
803 flat array (the field "pointsize" is the increment in the flat
804 array to get to the next point so for a dataset consisting only of
805 (x,y) pairs it would be 2).
806
807 - getAxes()
808
809 Gets an object with the axes settings as { xaxis, yaxis, x2axis,
810 y2axis }.
811
812 Various things are stuffed inside an axis object, e.g. you could
813 use getAxes().xaxis.ticks to find out what the ticks are for the
814 xaxis. Two other useful attributes are p2c and c2p, functions for
815 transforming from data point space to the canvas plot space and
816 back. Both returns values that are offset with the plot offset.
817
818 - getPlaceholder()
819
820 Returns placeholder that the plot was put into. This can be useful
821 for plugins for adding DOM elements or firing events.
822
823 - getCanvas()
824
825 Returns the canvas used for drawing in case you need to hack on it
826 yourself. You'll probably need to get the plot offset too.
827
828 - getPlotOffset()
829
830 Gets the offset that the grid has within the canvas as an object
831 with distances from the canvas edges as "left", "right", "top",
832 "bottom". I.e., if you draw a circle on the canvas with the center
833 placed at (left, top), its center will be at the top-most, left
834 corner of the grid.
835
836 - getOptions()
837
838 Gets the options for the plot, in a normalized format with default
839 values filled in.
840
841
842 Hooks
843 =====
844
845 In addition to the public methods, the Plot object also has some hooks
846 that can be used to modify the plotting process. You can install a
847 callback function at various points in the process, the function then
848 gets access to the internal data structures in Flot.
849
850 Here's an overview of the phases Flot goes through:
851
852 1. Plugin initialization, parsing options
853
854 2. Constructing the canvases used for drawing
855
856 3. Set data: parsing data specification, calculating colors,
857 copying raw data points into internal format,
858 normalizing them, finding max/min for axis auto-scaling
859
860 4. Grid setup: calculating axis spacing, ticks, inserting tick
861 labels, the legend
862
863 5. Draw: drawing the grid, drawing each of the series in turn
864
865 6. Setting up event handling for interactive features
866
867 7. Responding to events, if any
868
869 Each hook is simply a function which is put in the appropriate array.
870 You can add them through the "hooks" option, and they are also available
871 after the plot is constructed as the "hooks" attribute on the returned
872 plot object, e.g.
873
874 // define a simple draw hook
875 function hellohook(plot, canvascontext) { alert("hello!"); };
876
877 // pass it in, in an array since we might want to specify several
878 var plot = $.plot(placeholder, data, { hooks: { draw: [hellohook] } });
879
880 // we can now find it again in plot.hooks.draw[0] unless a plugin
881 // has added other hooks
882
883 The available hooks are described below. All hook callbacks get the
884 plot object as first parameter. You can find some examples of defined
885 hooks in the plugins bundled with Flot.
886
887 - processOptions [phase 1]
888
889 function(plot, options)
890
891 Called after Flot has parsed and merged options. Useful in the
892 instance where customizations beyond simple merging of default
893 values is needed. A plugin might use it to detect that it has been
894 enabled and then turn on or off other options.
895
896
897 - processRawData [phase 3]
898
899 function(plot, series, data, datapoints)
900
901 Called before Flot copies and normalizes the raw data for the given
902 series. If the function fills in datapoints.points with normalized
903 points and sets datapoints.pointsize to the size of the points,
904 Flot will skip the copying/normalization step for this series.
905
906 In any case, you might be interested in setting datapoints.format,
907 an array of objects for specifying how a point is normalized and
908 how it interferes with axis scaling.
909
910 The default format array for points is something along the lines of:
911
912 [
913 { x: true, number: true, required: true },
914 { y: true, number: true, required: true }
915 ]
916
917 The first object means that for the first coordinate it should be
918 taken into account when scaling the x axis, that it must be a
919 number, and that it is required - so if it is null or cannot be
920 converted to a number, the whole point will be zeroed out with
921 nulls. Beyond these you can also specify "defaultValue", a value to
922 use if the coordinate is null. This is for instance handy for bars
923 where one can omit the third coordinate (the bottom of the bar)
924 which then defaults to 0.
925
926
927 - processDatapoints [phase 3]
928
929 function(plot, series, datapoints)
930
931 Called after normalization of the given series but before finding
932 min/max of the data points. This hook is useful for implementing data
933 transformations. "datapoints" contains the normalized data points in
934 a flat array as datapoints.points with the size of a single point
935 given in datapoints.pointsize. Here's a simple transform that
936 multiplies all y coordinates by 2:
937
938 function multiply(plot, series, datapoints) {
939 var points = datapoints.points, ps = datapoints.pointsize;
940 for (var i = 0; i < points.length; i += ps)
941 points[i + 1] *= 2;
942 }
943
944 Note that you must leave datapoints in a good condition as Flot
945 doesn't check it or do any normalization on it afterwards.
946
947
948 - draw [phase 5]
949
950 function(plot, canvascontext)
951
952 Hook for drawing on the canvas. Called after the grid is drawn
953 (unless it's disabled) and the series have been plotted (in case
954 any points, lines or bars have been turned on). For examples of how
955 to draw things, look at the source code.
956
957
958 - bindEvents [phase 6]
959
960 function(plot, eventHolder)
961
962 Called after Flot has setup its event handlers. Should set any
963 necessary event handlers on eventHolder, a jQuery object with the
964 canvas, e.g.
965
966 function (plot, eventHolder) {
967 eventHolder.mousedown(function (e) {
968 alert("You pressed the mouse at " + e.pageX + " " + e.pageY);
969 });
970 }
971
972 Interesting events include click, mousemove, mouseup/down. You can
973 use all jQuery events. Usually, the event handlers will update the
974 state by drawing something (add a drawOverlay hook and call
975 triggerRedrawOverlay) or firing an externally visible event for
976 user code. See the crosshair plugin for an example.
977
978 Currently, eventHolder actually contains both the static canvas
979 used for the plot itself and the overlay canvas used for
980 interactive features because some versions of IE get the stacking
981 order wrong. The hook only gets one event, though (either for the
982 overlay or for the static canvas).
983
984
985 - drawOverlay [phase 7]
986
987 function (plot, canvascontext)
988
989 The drawOverlay hook is used for interactive things that need a
990 canvas to draw on. The model currently used by Flot works the way
991 that an extra overlay canvas is positioned on top of the static
992 canvas. This overlay is cleared and then completely redrawn
993 whenever something interesting happens. This hook is called when
994 the overlay canvas is to be redrawn.
995
996 "canvascontext" is the 2D context of the overlay canvas. You can
997 use this to draw things. You'll most likely need some of the
998 metrics computed by Flot, e.g. plot.width()/plot.height(). See the
999 crosshair plugin for an example.
1000
1001
1002
1003 Plugins
1004 -------
1005
1006 Plugins extend the functionality of Flot. To use a plugin, simply
1007 include its Javascript file after Flot in the HTML page.
1008
1009 If you're worried about download size/latency, you can concatenate all
1010 the plugins you use, and Flot itself for that matter, into one big file
1011 (make sure you get the order right), then optionally run it through a
1012 Javascript minifier such as YUI Compressor.
1013
1014 Here's a brief explanation of how the plugin plumbings work:
1015
1016 Each plugin registers itself in the global array $.plot.plugins. When
1017 you make a new plot object with $.plot, Flot goes through this array
1018 calling the "init" function of each plugin and merging default options
1019 from its "option" attribute. The init function gets a reference to the
1020 plot object created and uses this to register hooks and add new public
1021 methods if needed.
1022
1023 See the PLUGINS.txt file for details on how to write a plugin. As the
1024 above description hints, it's actually pretty easy.
1025