2015/03/11 16:27
阅读数 84

Consider a call to the plot function:

var plot = $.plot(placeholder, data, options)

The placeholder is a jQuery object or DOM element or jQuery expressionthat the plot will be put into. This placeholder needs to have itswidth and height set as explained in the README (go read that now ifyou haven't, it's short). The plot will modify some properties of theplaceholder so it's recommended you simply pass in a div that youdon't use for anything else. Make sure you check any fancy stylingyou apply to the div, e.g. background images have been reported to be aproblem on IE 7.

The plot function can also be used as a jQuery chainable property. This formnaturally can't return the plot object directly, but you can still access itvia the 'plot' data key, like this:

var plot = $("#placeholder").plot(data, options).data("plot");

The format of the data is documented below, as is the availableoptions. The plot object returned from the call has some methods youcan call. These are documented separately below.

Note that in general Flot gives no guarantees if you change any of theobjects you pass in to the plot function or get out of it sincethey're not necessarily deep-copied.

Data Format

The data is an array of data series:

[ series1, series2, ... ]

A series can either be raw data or an object with properties. The rawdata format is an array of points:

[ [x1, y1], [x2, y2], ... ]


[ [1, 3], [2, 14.01], [3.5, 3.14] ]

Note that to simplify the internal logic in Flot both the x and yvalues must be numbers (even if specifying time series, see below forhow to do this). This is a common problem because you might retrievedata from the database and serialize them directly to JSON withoutnoticing the wrong type. If you're getting mysterious errors, doublecheck that you're inputting numbers and not strings.

If a null is specified as a point or if one of the coordinates is nullor couldn't be converted to a number, the point is ignored whendrawing. As a special case, a null value for lines is interpreted as aline segment end, i.e. the points before and after the null value arenot connected.

Lines and points take two coordinates. For filled lines and bars, youcan specify a third coordinate which is the bottom of the filledarea/bar (defaults to 0).

The format of a single series object is as follows:

    color: color or number
    data: rawdata
    label: string
    lines: specific lines options
    bars: specific bars options
    points: specific points options
    xaxis: number
    yaxis: number
    clickable: boolean
    hoverable: boolean
    shadowSize: number
    highlightColor: color or number

You don't have to specify any of them except the data, the rest areoptions that will get default values. Typically you'd only specifylabel and data, like this:

    label: "y = 3",
    data: [[0, 3], [10, 3]]

The label is used for the legend, if you don't specify one, the serieswill not show up in the legend.

If you don't specify color, the series will get a color from theauto-generated colors. The color is either a CSS color specification(like "rgb(255, 100, 123)") or an integer that specifies which ofauto-generated colors to select, e.g. 0 will get color no. 0, etc.

The latter is mostly useful if you let the user add and remove series,in which case you can hard-code the color index to prevent the colorsfrom jumping around between the series.

The "xaxis" and "yaxis" options specify which axis to use. The axesare numbered from 1 (default), so { yaxis: 2} means that the seriesshould be plotted against the second y axis.

"clickable" and "hoverable" can be set to false to disableinteractivity for specific series if interactivity is turned on inthe plot, see below.

The rest of the options are all documented below as they are the sameas the default options passed in via the options parameter in the plotcommmand. When you specify them for a specific data series, they willoverride the default options for the plot for that data series.

Here's a complete example of a simple data specification:

[ { label: "Foo", data: [ [10, 1], [17, -14], [30, 5] ] },
  { label: "Bar", data: [ [11, 13], [19, 11], [30, -7] ] }

Plot Options

All options are completely optional. They are documented individuallybelow, to change them you just specify them in an object, e.g.

var options = {
    series: {
        lines: { show: true },
        points: { show: true }

$.plot(placeholder, data, options);

Customizing the legend

legend: {
    show: boolean
    labelFormatter: null or (fn: string, series object -> string)
    labelBoxBorderColor: color
    noColumns: number
    position: "ne" or "nw" or "se" or "sw"
    margin: number of pixels or [x margin, y margin]
    backgroundColor: null or color
    backgroundOpacity: number between 0 and 1
    container: null or jQuery object/DOM element/jQuery expression
    sorted: null/false, true, "ascending", "descending", "reverse", or a comparator

The legend is generated as a table with the data series labels andsmall label boxes with the color of the series. If you want to formatthe labels in some way, e.g. make them to links, you can pass in afunction for "labelFormatter". Here's an example that makes themclickable:

labelFormatter: function(label, series) {
    // series is the series object for the label
    return '<a href="#' + label + '">' + label + '</a>';

To prevent a series from showing up in the legend, simply have the functionreturn null.

"noColumns" is the number of columns to divide the legend table into."position" specifies the overall placement of the legend within theplot (top-right, top-left, etc.) and margin the distance to the plotedge (this can be either a number or an array of two numbers like [x,y]). "backgroundColor" and "backgroundOpacity" specifies thebackground. The default is a partly transparent auto-detectedbackground.

If you want the legend to appear somewhere else in the DOM, you canspecify "container" as a jQuery object/expression to put the legendtable into. The "position" and "margin" etc. options will then beignored. Note that Flot will overwrite the contents of the container.

Legend entries appear in the same order as their series by default. If "sorted"is "reverse" then they appear in the opposite order from their series. To sortthem alphabetically, you can specify true, "ascending" or "descending", wheretrue and "ascending" are equivalent.

You can also provide your own comparator function that accepts twoobjects with "label" and "color" properties, and returns zero if theyare equal, a positive value if the first is greater than the second,and a negative value if the first is less than the second.

sorted: function(a, b) {
    // sort alphabetically in ascending order
    return a.label == b.label ? 0 : (
        a.label > b.label ? 1 : -1

Customizing the axes

xaxis, yaxis: {
    show: null or true/false
    position: "bottom" or "top" or "left" or "right"
    mode: null or "time" ("time" requires jquery.flot.time.js plugin)
    timezone: null, "browser" or timezone (only makes sense for mode: "time")

    color: null or color spec
    tickColor: null or color spec
    font: null or font spec object

    min: null or number
    max: null or number
    autoscaleMargin: null or number

    transform: null or fn: number -> number
    inverseTransform: null or fn: number -> number

    ticks: null or number or ticks array or (fn: axis -> ticks array)
    tickSize: number or array
    minTickSize: number or array
    tickFormatter: (fn: number, object -> string) or string
    tickDecimals: null or number

    labelWidth: null or number
    labelHeight: null or number
    reserveSpace: null or true

    tickLength: null or number

    alignTicksWithAxis: null or number

All axes have the same kind of options. The following describes how toconfigure one axis, see below for what to do if you've got more thanone x axis or y axis.

If you don't set the "show" option (i.e. it is null), visibility isauto-detected, i.e. the axis will show up if there's data associatedwith it. You can override this by setting the "show" option to true orfalse.

The "position" option specifies where the axis is placed, bottom ortop for x axes, left or right for y axes. The "mode" option determineshow the data is interpreted, the default of null means as decimalnumbers. Use "time" for time series data; see the time series datasection. The time plugin (jquery.flot.time.js) is required for timeseries support.

The "color" option determines the color of the line and ticks for the axis, anddefaults to the grid color with transparency. For more fine-grained control youcan also set the color of the ticks separately with "tickColor".

You can customize the font and color used to draw the axis tick labels with CSSor directly via the "font" option. When "font" is null - the default - eachtick label is given the 'flot-tick-label' class. For compatibility with Flot0.7 and earlier the labels are also given the 'tickLabel' class, but this isdeprecated and scheduled to be removed with the release of version 1.0.0.

To enable more granular control over styles, labels are divided between a setof text containers, with each holding the labels for one axis. These containersare given the classes 'flot-[x|y]-axis', and 'flot-[x|y]#-axis', where '#' isthe number of the axis when there are multiple axes. For example, the x-axislabels for a simple plot with only a single x-axis might look like this:

<div class='flot-x-axis flot-x1-axis'>
    <div class='flot-tick-label'>January 2013</div>

For direct control over label styles you can also provide "font" as an objectwith this format:

    size: 11,
    lineHeight: 13,
    style: "italic",
    weight: "bold",
    family: "sans-serif",
    variant: "small-caps",
    color: "#545454"

The size and lineHeight must be expressed in pixels; CSS units such as 'em'or 'smaller' are not allowed.

The options "min"/"max" are the precise minimum/maximum value on thescale. If you don't specify either of them, a value will automaticallybe chosen based on the minimum/maximum data values. Note that Flotalways examines all the data values you feed to it, even if arestriction on another axis may make some of them invisible (thismakes interactive use more stable).

The "autoscaleMargin" is a bit esoteric: it's the fraction of marginthat the scaling algorithm will add to avoid that the outermost pointsends up on the grid border. Note that this margin is only applied whena min or max value is not explicitly set. If a margin is specified,the plot will furthermore extend the axis end-point to the nearestwhole tick. The default value is "null" for the x axes and 0.02 for yaxes which seems appropriate for most cases.

"transform" and "inverseTransform" are callbacks you can put in tochange the way the data is drawn. You can design a function tocompress or expand certain parts of the axis non-linearly, e.g.suppress weekends or compress far away points with a logarithm or someother means. When Flot draws the plot, each value is first put throughthe transform function. Here's an example, the x axis can be turnedinto a natural logarithm axis with the following code:

xaxis: {
    transform: function (v) { return Math.log(v); },
    inverseTransform: function (v) { return Math.exp(v); }

Similarly, for reversing the y axis so the values appear in inverseorder:

yaxis: {
    transform: function (v) { return -v; },
    inverseTransform: function (v) { return -v; }

Note that for finding extrema, Flot assumes that the transformfunction does not reorder values (it should be monotone).

The inverseTransform is simply the inverse of the transform function(so v == inverseTransform(transform(v)) for all relevant v). It isrequired for converting from canvas coordinates to data coordinates,e.g. for a mouse interaction where a certain pixel is clicked. If youdon't use any interactive features of Flot, you may not need it.

The rest of the options deal with the ticks.

If you don't specify any ticks, a tick generator algorithm will makesome for you. The algorithm has two passes. It first estimates howmany ticks would be reasonable and uses this number to compute a niceround tick interval size. Then it generates the ticks.

You can specify how many ticks the algorithm aims for by setting"ticks" to a number. The algorithm always tries to generate reasonablyround tick values so even if you ask for three ticks, you might getfive if that fits better with the rounding. If you don't want anyticks at all, set "ticks" to 0 or an empty array.

Another option is to skip the rounding part and directly set the tickinterval size with "tickSize". If you set it to 2, you'll get ticks at2, 4, 6, etc. Alternatively, you can specify that you just don't wantticks at a size less than a specific tick size with "minTickSize".Note that for time series, the format is an array like [2, "month"],see the next section.

If you want to completely override the tick algorithm, you can specifyan array for "ticks", either like this:

ticks: [0, 1.2, 2.4]

Or like this where the labels are also customized:

ticks: [[0, "zero"], [1.2, "one mark"], [2.4, "two marks"]]

You can mix the two if you like.

For extra flexibility you can specify a function as the "ticks"parameter. The function will be called with an object with the axismin and max and should return a ticks array. Here's a simplistic tickgenerator that spits out intervals of pi, suitable for use on the xaxis for trigonometric functions:

function piTickGenerator(axis) {
    var res = [], i = Math.floor(axis.min / Math.PI);
    do {
        var v = i * Math.PI;
        res.push([v, i + "\u03c0"]);
    } while (v < axis.max);
    return res;

You can control how the ticks look like with "tickDecimals", thenumber of decimals to display (default is auto-detected).

Alternatively, for ultimate control over how ticks are formatted you canprovide a function to "tickFormatter". The function is passed twoparameters, the tick value and an axis object with information, andshould return a string. The default formatter looks like this:

function formatter(val, axis) {
    return val.toFixed(axis.tickDecimals);

The axis object has "min" and "max" with the range of the axis,"tickDecimals" with the number of decimals to round the value to and"tickSize" with the size of the interval between ticks as calculatedby the automatic axis scaling algorithm (or specified by you). Here'san example of a custom formatter:

function suffixFormatter(val, axis) {
    if (val > 1000000)
        return (val / 1000000).toFixed(axis.tickDecimals) + " MB";
    else if (val > 1000)
        return (val / 1000).toFixed(axis.tickDecimals) + " kB";
        return val.toFixed(axis.tickDecimals) + " B";

"labelWidth" and "labelHeight" specifies a fixed size of the ticklabels in pixels. They're useful in case you need to align severalplots. "reserveSpace" means that even if an axis isn't shown, Flotshould reserve space for it - it is useful in combination withlabelWidth and labelHeight for aligning multi-axis charts.

"tickLength" is the length of the tick lines in pixels. By default, theinnermost axes will have ticks that extend all across the plot, whileany extra axes use small ticks. A value of null means use the default,while a number means small ticks of that length - set it to 0 to hidethe lines completely.

If you set "alignTicksWithAxis" to the number of another axis, e.g.alignTicksWithAxis: 1, Flot will ensure that the autogenerated ticksof this axis are aligned with the ticks of the other axis. This mayimprove the looks, e.g. if you have one y axis to the left and one tothe right, because the grid lines will then match the ticks in bothends. The trade-off is that the forced ticks won't necessarily be atnatural places.

Multiple axes

If you need more than one x axis or y axis, you need to specify foreach data series which axis they are to use, as described under theformat of the data series, e.g. { data: [...], yaxis: 2 } specifiesthat a series should be plotted against the second y axis.

To actually configure that axis, you can't use the xaxis/yaxis optionsdirectly - instead there are two arrays in the options:

xaxes: []
yaxes: []

Here's an example of configuring a single x axis and two y axes (wecan leave options of the first y axis empty as the defaults are fine):

    xaxes: [ { position: "top" } ],
    yaxes: [ { }, { position: "right", min: 20 } ]

The arrays get their default values from the xaxis/yaxis settings, sosay you want to have all y axes start at zero, you can simply specifyyaxis: { min: 0 } instead of adding a min parameter to all the axes.

Generally, the various interfaces in Flot dealing with data pointseither accept an xaxis/yaxis parameter to specify which axis number touse (starting from 1), or lets you specify the coordinate directly asx2/x3/... or x2axis/x3axis/... instead of "x" or "xaxis".

Time series data

Please note that it is now required to include the time plugin,jquery.flot.time.js, for time series support.

Time series are a bit more difficult than scalar data becausecalendars don't follow a simple base 10 system. For many cases, Flotabstracts most of this away, but it can still be a bit difficult toget the data into Flot. So we'll first discuss the data format.

The time series support in Flot is based on Javascript timestamps,i.e. everywhere a time value is expected or handed over, a Javascripttimestamp number is used. This is a number, not a Date object. AJavascript timestamp is the number of milliseconds since January 1,1970 00:00:00 UTC. This is almost the same as Unix timestamps, except it'sin milliseconds, so remember to multiply by 1000!

You can see a timestamp like this

alert((new Date()).getTime())

There are different schools of thought when it comes to display oftimestamps. Many will want the timestamps to be displayed according toa certain time zone, usually the time zone in which the data has beenproduced. Some want the localized experience, where the timestamps aredisplayed according to the local time of the visitor. Flot supportsboth. Optionally you can include a third-party library to getadditional timezone support.

Default behavior is that Flot always displays timestamps according toUTC. The reason being that the core Javascript Date object does notsupport other fixed time zones. Often your data is at another timezone, so it may take a little bit of tweaking to work around thislimitation.

The easiest way to think about it is to pretend that the dataproduction time zone is UTC, even if it isn't. So if you have adatapoint at 2002-02-20 08:00, you can generate a timestamp for eighto'clock UTC even if it really happened eight o'clock UTC+0200.

In PHP you can get an appropriate timestamp with:

strtotime("2002-02-20 UTC") * 1000

In Python you can get it with something like:

calendar.timegm(datetime_object.timetuple()) * 1000

In .NET you can get it with something like:

public static int GetJavascriptTimestamp(System.DateTime input)
    System.TimeSpan span = new System.TimeSpan(System.DateTime.Parse("1/1/1970").Ticks);
    System.DateTime time = input.Subtract(span);
    return (long)(time.Ticks / 10000);

Javascript also has some support for parsing date strings, so it ispossible to generate the timestamps manually client-side.

If you've already got the real UTC timestamp, it's too late to use thepretend trick described above. But you can fix up the timestamps byadding the time zone offset, e.g. for UTC+0200 you would add 2 hoursto the UTC timestamp you got. Then it'll look right on the plot. Mostprogramming environments have some means of getting the timezoneoffset for a specific date (note that you need to get the offset foreach individual timestamp to account for daylight savings).

The alternative with core Javascript is to interpret the timestampsaccording to the time zone that the visitor is in, which means thatthe ticks will shift with the time zone and daylight savings of eachvisitor. This behavior is enabled by setting the axis option"timezone" to the value "browser".

If you need more time zone functionality than this, there is stillanother option. If you include the "timezone-js" libraryhttps://github.com/mde/timezone-js in the page and set axis.timezoneto a value recognized by said library, Flot will use timezone-js tointerpret the timestamps according to that time zone.

Once you've gotten the timestamps into the data and specified "time"as the axis mode, Flot will automatically generate relevant ticks andformat them. As always, you can tweak the ticks via the "ticks" option

  • just remember that the values should be timestamps (numbers), notDate objects.

Tick generation and formatting can also be controlled separatelythrough the following axis options:

minTickSize: array
timeformat: null or format string
monthNames: null or array of size 12 of strings
dayNames: null or array of size 7 of strings
twelveHourClock: boolean

Here "timeformat" is a format string to use. You might use it likethis:

xaxis: {
    mode: "time",
    timeformat: "%Y/%m/%d"

This will result in tick labels like "2000/12/24". A subset of thestandard strftime specifiers are supported (plus the nonstandard %q):

%a: weekday name (customizable)
%b: month name (customizable)
%d: day of month, zero-padded (01-31)
%e: day of month, space-padded ( 1-31)
%H: hours, 24-hour time, zero-padded (00-23)
%I: hours, 12-hour time, zero-padded (01-12)
%m: month, zero-padded (01-12)
%M: minutes, zero-padded (00-59)
%q: quarter (1-4)
%S: seconds, zero-padded (00-59)
%y: year (two digits)
%Y: year (four digits)
%p: am/pm
%P: AM/PM (uppercase version of %p)
%w: weekday as number (0-6, 0 being Sunday)

Flot 0.8 switched from %h to the standard %H hours specifier. The %h specifieris still available, for backwards-compatibility, but is deprecated andscheduled to be removed permanently with the release of version 1.0.

You can customize the month names with the "monthNames" option. Forinstance, for Danish you might specify:

monthNames: ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]

Similarly you can customize the weekday names with the "dayNames"option. An example in French:

dayNames: ["dim", "lun", "mar", "mer", "jeu", "ven", "sam"]

If you set "twelveHourClock" to true, the autogenerated timestampswill use 12 hour AM/PM timestamps instead of 24 hour. This onlyapplies if you have not set "timeformat". Use the "%I" and "%p" or"%P" options if you want to build your own format string with 12-hourtimes.

If the Date object has a strftime property (and it is a function), itwill be used instead of the built-in formatter. Thus you can includea strftime library such as http://hacks.bluesmoon.info/strftime/ formore powerful date/time formatting.

If everything else fails, you can control the formatting by specifyinga custom tick formatter function as usual. Here's a simple examplewhich will format December 24 as 24/12:

tickFormatter: function (val, axis) {
    var d = new Date(val);
    return d.getUTCDate() + "/" + (d.getUTCMonth() + 1);

Note that for the time mode "tickSize" and "minTickSize" are a bitspecial in that they are arrays on the form "[value, unit]" where unitis one of "second", "minute", "hour", "day", "month" and "year". Soyou can specify

minTickSize: [1, "month"]

to get a tick interval size of at least 1 month and correspondingly,if axis.tickSize is [2, "day"] in the tick formatter, the ticks havebeen produced with two days in-between.

Customizing the data series

series: {
    lines, points, bars: {
        show: boolean
        lineWidth: number
        fill: boolean or number
        fillColor: null or color/gradient

    lines, bars: {
        zero: boolean

    points: {
        radius: number
        symbol: "circle" or function

    bars: {
        barWidth: number
        align: "left", "right" or "center"
        horizontal: boolean

    lines: {
        steps: boolean

    shadowSize: number
    highlightColor: color or number

colors: [ color1, color2, ... ]

The options inside "series: {}" are copied to each of the series. Soyou can specify that all series should have bars by putting it in theglobal options, or override it for individual series by specifyingbars in a particular the series object in the array of data.

The most important options are "lines", "points" and "bars" thatspecify whether and how lines, points and bars should be shown foreach data series. In case you don't specify anything at all, Flot willdefault to showing lines (you can turn this off withlines: { show: false }). You can specify the various typesindependently of each other, and Flot will happily draw each of themin turn (this is probably only useful for lines and points), e.g.

var options = {
    series: {
        lines: { show: true, fill: true, fillColor: "rgba(255, 255, 255, 0.8)" },
        points: { show: true, fill: false }

"lineWidth" is the thickness of the line or outline in pixels. You canset it to 0 to prevent a line or outline from being drawn; this willalso hide the shadow.

"fill" is whether the shape should be filled. For lines, this producesarea graphs. You can use "fillColor" to specify the color of the fill.If "fillColor" evaluates to false (default for everything exceptpoints which are filled with white), the fill color is auto-set to thecolor of the data series. You can adjust the opacity of the fill bysetting fill to a number between 0 (fully transparent) and 1 (fullyopaque).

For bars, fillColor can be a gradient, see the gradient documentationbelow. "barWidth" is the width of the bars in units of the x axis (orthe y axis if "horizontal" is true), contrary to most other measuresthat are specified in pixels. For instance, for time series the unitis milliseconds so 24 * 60 * 60 * 1000 produces bars with the width ofa day. "align" specifies whether a bar should be left-aligned(default), right-aligned or centered on top of the value it represents. When "horizontal" is on, the bars are drawn horizontally, i.e. from the y axis instead of the x axis; note that the bar end points are stilldefined in the same way so you'll probably want to swap thecoordinates if you've been plotting vertical bars first.

Area and bar charts normally start from zero, regardless of the data's range.This is because they convey information through size, and starting from adifferent value would distort their meaning. In cases where the fill is purelyfor decorative purposes, however, "zero" allows you to override this behavior.It defaults to true for filled lines and bars; setting it to false tells theseries to use the same automatic scaling as an un-filled line.

For lines, "steps" specifies whether two adjacent data points areconnected with a straight (possibly diagonal) line or with first ahorizontal and then a vertical line. Note that this transforms thedata by adding extra points.

For points, you can specify the radius and the symbol. The onlybuilt-in symbol type is circles, for other types you can use a pluginor define them yourself by specifying a callback:

function cross(ctx, x, y, radius, shadow) {
    var size = radius * Math.sqrt(Math.PI) / 2;
    ctx.moveTo(x - size, y - size);
    ctx.lineTo(x + size, y + size);
    ctx.moveTo(x - size, y + size);
    ctx.lineTo(x + size, y - size);

The parameters are the drawing context, x and y coordinates of thecenter of the point, a radius which corresponds to what the circlewould have used and whether the call is to draw a shadow (due tolimited canvas support, shadows are currently faked through extradraws). It's good practice to ensure that the area covered by thesymbol is the same as for the circle with the given radius, thisensures that all symbols have approximately the same visual weight.

"shadowSize" is the default size of shadows in pixels. Set it to 0 toremove shadows.

"highlightColor" is the default color of the translucent overlay usedto highlight the series when the mouse hovers over it.

The "colors" array specifies a default color theme to get colors forthe data series from. You can specify as many colors as you like, likethis:

colors: ["#d18b2c", "#dba255", "#919733"]

If there are more data series than colors, Flot will try to generateextra colors by lightening and darkening colors in the theme.

Customizing the grid

grid: {
    show: boolean
    aboveData: boolean
    color: color
    backgroundColor: color/gradient or null
    margin: number or margin object
    labelMargin: number
    axisMargin: number
    markings: array of markings or (fn: axes -> array of markings)
    borderWidth: number or object with "top", "right", "bottom" and "left" properties with different widths
    borderColor: color or null or object with "top", "right", "bottom" and "left" properties with different colors
    minBorderMargin: number or null
    clickable: boolean
    hoverable: boolean
    autoHighlight: boolean
    mouseActiveRadius: number

interaction: {
    redrawOverlayInterval: number or -1

The grid is the thing with the axes and a number of ticks. Many of thethings in the grid are configured under the individual axes, but notall. "color" is the color of the grid itself whereas "backgroundColor"specifies the background color inside the grid area, here null meansthat the background is transparent. You can also set a gradient, seethe gradient documentation below.

You can turn off the whole grid including tick labels by setting"show" to false. "aboveData" determines whether the grid is drawnabove the data or below (below is default).

"margin" is the space in pixels between the canvas edge and the grid,which can be either a number or an object with individual margins foreach side, in the form:

margin: {
    top: top margin in pixels
    left: left margin in pixels
    bottom: bottom margin in pixels
    right: right margin in pixels

"labelMargin" is the space in pixels between tick labels and axisline, and "axisMargin" is the space in pixels between axes when thereare two next to each other.

"borderWidth" is the width of the border around the plot. Set it to 0to disable the border. Set it to an object with "top", "right","bottom" and "left" properties to use different widths. You canalso set "borderColor" if you want the border to have a different colorthan the grid lines. Set it to an object with "top", "right", "bottom"and "left" properties to use different colors. "minBorderMargin" controlsthe default minimum margin around the border - it's used to make surethat points aren't accidentally clipped by the canvas edge so by defaultthe value is computed from the point radius.

"markings" is used to draw simple lines and rectangular areas in thebackground of the plot. You can either specify an array of ranges onthe form { xaxis: { from, to }, yaxis: { from, to } } (with multipleaxes, you can specify coordinates for other axes instead, e.g. asx2axis/x3axis/...) or with a function that returns such an array giventhe axes for the plot in an object as the first parameter.

You can set the color of markings by specifying "color" in the rangesobject. Here's an example array:

markings: [ { xaxis: { from: 0, to: 2 }, yaxis: { from: 10, to: 10 }, color: "#bb0000" }, ... ]

If you leave out one of the values, that value is assumed to go to theborder of the plot. So for example if you only specify { xaxis: {from: 0, to: 2 } } it means an area that extends from the top to thebottom of the plot in the x range 0-2.

A line is drawn if from and to are the same, e.g.

markings: [ { yaxis: { from: 1, to: 1 } }, ... ]

would draw a line parallel to the x axis at y = 1. You can control theline width with "lineWidth" in the range object.

An example function that makes vertical stripes might look like this:

markings: function (axes) {
    var markings = [];
    for (var x = Math.floor(axes.xaxis.min); x < axes.xaxis.max; x += 2)
        markings.push({ xaxis: { from: x, to: x + 1 } });
    return markings;

If you set "clickable" to true, the plot will listen for click eventson the plot area and fire a "plotclick" event on the placeholder witha position and a nearby data item object as parameters. The coordinatesare available both in the unit of the axes (not in pixels) and inglobal screen coordinates.

Likewise, if you set "hoverable" to true, the plot will listen formouse move events on the plot area and fire a "plothover" event withthe same parameters as the "plotclick" event. If "autoHighlight" istrue (the default), nearby data items are highlighted automatically.If needed, you can disable highlighting and control it yourself withthe highlight/unhighlight plot methods described elsewhere.

You can use "plotclick" and "plothover" events like this:

$.plot($("#placeholder"), [ d ], { grid: { clickable: true } });

$("#placeholder").bind("plotclick", function (event, pos, item) {
    alert("You clicked at " + pos.x + ", " + pos.y);
    // axis coordinates for other axes, if present, are in pos.x2, pos.x3, ...
    // if you need global screen coordinates, they are pos.pageX, pos.pageY

    if (item) {
        highlight(item.series, item.datapoint);
        alert("You clicked a point!");

The item object in this example is either null or a nearby object on the form:

item: {
    datapoint: the point, e.g. [0, 2]
    dataIndex: the index of the point in the data array
    series: the series object
    seriesIndex: the index of the series
    pageX, pageY: the global screen coordinates of the point

For instance, if you have specified the data like this

$.plot($("#placeholder"), [ { label: "Foo", data: [[0, 10], [7, 3]] } ], ...);

and the mouse is near the point (7, 3), "datapoint" is [7, 3],"dataIndex" will be 1, "series" is a normalized series object withamong other things the "Foo" label in series.label and the color inseries.color, and "seriesIndex" is 0. Note that plugins and optionsthat transform the data can shift the indexes from what you specifiedin the original data array.

If you use the above events to update some other information and wantto clear out that info in case the mouse goes away, you'll probablyalso need to listen to "mouseout" events on the placeholder div.

"mouseActiveRadius" specifies how far the mouse can be from an itemand still activate it. If there are two or more points within thisradius, Flot chooses the closest item. For bars, the top-most bar(from the latest specified data series) is chosen.

If you want to disable interactivity for a specific data series, youcan set "hoverable" and "clickable" to false in the options for thatseries, like this:

{ data: [...], label: "Foo", clickable: false }

"redrawOverlayInterval" specifies the maximum time to delay a redrawof interactive things (this works as a rate limiting device). Thedefault is capped to 60 frames per second. You can set it to -1 todisable the rate limiting.

Specifying gradients

A gradient is specified like this:

{ colors: [ color1, color2, ... ] }

For instance, you might specify a background on the grid going fromblack to gray like this:

grid: {
    backgroundColor: { colors: ["#000", "#999"] }

For the series you can specify the gradient as an object thatspecifies the scaling of the brightness and the opacity of the seriescolor, e.g.

{ colors: [{ opacity: 0.8 }, { brightness: 0.6, opacity: 0.8 } ] }

where the first color simply has its alpha scaled, whereas the secondis also darkened. For instance, for bars the following makes the barsgradually disappear, without outline:

bars: {
    show: true,
    lineWidth: 0,
    fill: true,
    fillColor: { colors: [ { opacity: 0.8 }, { opacity: 0.1 } ] }

Flot currently only supports vertical gradients drawn from top tobottom because that's what works with IE.

Plot Methods

The Plot object returned from the plot function has some methods youcan call:

  • highlight(series, datapoint)

    Highlight a specific datapoint in the data series. You can eitherspecify the actual objects, e.g. if you got them from a"plotclick" event, or you can specify the indices, e.g.highlight(1, 3) to highlight the fourth point in the second series(remember, zero-based indexing).

  • unhighlight(series, datapoint) or unhighlight()

    Remove the highlighting of the point, same parameters ashighlight.

    If you call unhighlight with no parameters, e.g. asplot.unhighlight(), all current highlights are removed.

  • setData(data)

    You can use this to reset the data used. Note that axis scaling,ticks, legend etc. will not be recomputed (use setupGrid() to dothat). You'll probably want to call draw() afterwards.

    You can use this function to speed up redrawing a small plot ifyou know that the axes won't change. Put in the new data withsetData(newdata), call draw(), and you're good to go. Note thatfor large datasets, almost all the time is consumed in draw()plotting the data so in this case don't bother.

  • setupGrid()

    Recalculate and set axis scaling, ticks, legend etc.

    Note that because of the drawing model of the canvas, thisfunction will immediately redraw (actually reinsert in the DOM)the labels and the legend, but not the actual tick lines becausethey're drawn on the canvas. You need to call draw() to get thecanvas redrawn.

  • draw()

    Redraws the plot canvas.

  • triggerRedrawOverlay()

    Schedules an update of an overlay canvas used for drawinginteractive things like a selection and point highlights. Thisis mostly useful for writing plugins. The redraw doesn't happenimmediately, instead a timer is set to catch multiple successiveredraws (e.g. from a mousemove). You can get to the overlay bysetting up a drawOverlay hook.

  • width()/height()

    Gets the width and height of the plotting area inside the grid.This is smaller than the canvas or placeholder dimensions as someextra space is needed (e.g. for labels).

  • offset()

    Returns the offset of the plotting area inside the grid relativeto the document, useful for instance for calculating mousepositions (event.pageX/Y minus this offset is the pixel positioninside the plot).

  • pointOffset({ x: xpos, y: ypos })

    Returns the calculated offset of the data point at (x, y) in dataspace within the placeholder div. If you are working with multipleaxes, you can specify the x and y axis references, e.g.

    o = pointOffset({ x: xpos, y: ypos, xaxis: 2, yaxis: 3 })
      // o.left and o.top now contains the offset within the div
  • resize()

    Tells Flot to resize the drawing canvas to the size of theplaceholder. You need to run setupGrid() and draw() afterwards ascanvas resizing is a destructive operation. This is usedinternally by the resize plugin.

  • shutdown()

    Cleans up any event handlers Flot has currently registered. Thisis used internally.

There are also some members that let you peek inside the internalworkings of Flot which is useful in some cases. Note that if you changesomething in the objects returned, you're changing the objects used byFlot to keep track of its state, so be careful.

  • getData()

    Returns an array of the data series currently used in normalizedform with missing settings filled in according to the globaloptions. So for instance to find out what color Flot has assignedto the data series, you could do this:

    var series = plot.getData();
    for (var i = 0; i < series.length; ++i)

    A notable other interesting field besides color is datapointswhich has a field "points" with the normalized data points in aflat array (the field "pointsize" is the increment in the flatarray to get to the next point so for a dataset consisting only of(x,y) pairs it would be 2).

  • getAxes()

    Gets an object with the axes. The axes are returned as theattributes of the object, so for instance getAxes().xaxis is thex axis.

    Various things are stuffed inside an axis object, e.g. you coulduse getAxes().xaxis.ticks to find out what the ticks are for thexaxis. Two other useful attributes are p2c and c2p, functions fortransforming from data point space to the canvas plot space andback. Both returns values that are offset with the plot offset.Check the Flot source code for the complete set of attributes (oroutput an axis with console.log() and inspect it).

    With multiple axes, the extra axes are returned as x2axis, x3axis,etc., e.g. getAxes().y2axis is the second y axis. You can checky2axis.used to see whether the axis is associated with any datapoints and y2axis.show to see if it is currently shown.

  • getPlaceholder()

    Returns placeholder that the plot was put into. This can be usefulfor plugins for adding DOM elements or firing events.

  • getCanvas()

    Returns the canvas used for drawing in case you need to hack on ityourself. You'll probably need to get the plot offset too.

  • getPlotOffset()

    Gets the offset that the grid has within the canvas as an objectwith distances from the canvas edges as "left", "right", "top","bottom". I.e., if you draw a circle on the canvas with the centerplaced at (left, top), its center will be at the top-most, leftcorner of the grid.

  • getOptions()

    Gets the options for the plot, normalized, with default valuesfilled in. You get a reference to actual values used by Flot, soif you modify the values in here, Flot will use the new values.If you change something, you probably have to call draw() orsetupGrid() or triggerRedrawOverlay() to see the change.


In addition to the public methods, the Plot object also has some hooksthat can be used to modify the plotting process. You can install acallback function at various points in the process, the function thengets access to the internal data structures in Flot.

Here's an overview of the phases Flot goes through:

  1. Plugin initialization, parsing options

  2. Constructing the canvases used for drawing

  3. Set data: parsing data specification, calculating colors, copying raw data points into internal format, normalizing them, finding max/min for axis auto-scaling

  4. Grid setup: calculating axis spacing, ticks, inserting tick labels, the legend

  5. Draw: drawing the grid, drawing each of the series in turn

  6. Setting up event handling for interactive features

  7. Responding to events, if any

  8. Shutdown: this mostly happens in case a plot is overwritten

Each hook is simply a function which is put in the appropriate array.You can add them through the "hooks" option, and they are also availableafter the plot is constructed as the "hooks" attribute on the returnedplot object, e.g.

// define a simple draw hook
  function hellohook(plot, canvascontext) { alert("hello!"); };

  // pass it in, in an array since we might want to specify several
  var plot = $.plot(placeholder, data, { hooks: { draw: [hellohook] } });

  // we can now find it again in plot.hooks.draw[0] unless a plugin
  // has added other hooks

The available hooks are described below. All hook callbacks get theplot object as first parameter. You can find some examples of definedhooks in the plugins bundled with Flot.

  • processOptions [phase 1]

    function(plot, options)

    Called after Flot has parsed and merged options. Useful in theinstance where customizations beyond simple merging of defaultvalues is needed. A plugin might use it to detect that it has beenenabled and then turn on or off other options.

  • processRawData [phase 3]

    function(plot, series, data, datapoints)

    Called before Flot copies and normalizes the raw data for the givenseries. If the function fills in datapoints.points with normalizedpoints and sets datapoints.pointsize to the size of the points,Flot will skip the copying/normalization step for this series.

    In any case, you might be interested in setting datapoints.format,an array of objects for specifying how a point is normalized andhow it interferes with axis scaling. It accepts the following options:

        x, y: boolean,
        number: boolean,
        required: boolean,
        defaultValue: value,
        autoscale: boolean

    "x" and "y" specify whether the value is plotted against the x or y axis,and is currently used only to calculate axis min-max ranges. The defaultformat array, for example, looks like this:

        { x: true, number: true, required: true },
        { y: true, number: true, required: true }

    This indicates that a point, i.e. [0, 25], consists of two values, with thefirst being plotted on the x axis and the second on the y axis.

    If "number" is true, then the value must be numeric, and is set to null ifit cannot be converted to a number.

    "defaultValue" provides a fallback in case the original value is null. Thisis for instance handy for bars, where one can omit the third coordinate(the bottom of the bar), which then defaults to zero.

    If "required" is true, then the value must exist (be non-null) for thepoint as a whole to be valid. If no value is provided, then the entirepoint is cleared out with nulls, turning it into a gap in the series.

    "autoscale" determines whether the value is considered when calculating anautomatic min-max range for the axes that the value is plotted against.

  • processDatapoints [phase 3]

    function(plot, series, datapoints)

    Called after normalization of the given series but before findingmin/max of the data points. This hook is useful for implementing datatransformations. "datapoints" contains the normalized data points ina flat array as datapoints.points with the size of a single pointgiven in datapoints.pointsize. Here's a simple transform thatmultiplies all y coordinates by 2:

    function multiply(plot, series, datapoints) {
        var points = datapoints.points, ps = datapoints.pointsize;
        for (var i = 0; i < points.length; i += ps)
            points[i + 1] *= 2;

    Note that you must leave datapoints in a good condition as Flotdoesn't check it or do any normalization on it afterwards.

  • processOffset [phase 4]

    function(plot, offset)

    Called after Flot has initialized the plot's offset, but before itdraws any axes or plot elements. This hook is useful for customizingthe margins between the grid and the edge of the canvas. "offset" isan object with attributes "top", "bottom", "left" and "right",corresponding to the margins on the four sides of the plot.

  • drawBackground [phase 5]

    function(plot, canvascontext)

    Called before all other drawing operations. Used to draw backgroundsor other custom elements before the plot or axes have been drawn.

  • drawSeries [phase 5]

    function(plot, canvascontext, series)

    Hook for custom drawing of a single series. Called just before thestandard drawing routine has been called in the loop that drawseach series.

  • draw [phase 5]

    function(plot, canvascontext)

    Hook for drawing on the canvas. Called after the grid is drawn(unless it's disabled or grid.aboveData is set) and the series havebeen plotted (in case any points, lines or bars have been turnedon). For examples of how to draw things, look at the source code.

  • bindEvents [phase 6]

    function(plot, eventHolder)

    Called after Flot has setup its event handlers. Should set anynecessary event handlers on eventHolder, a jQuery object with thecanvas, e.g.

    function (plot, eventHolder) {
        eventHolder.mousedown(function (e) {
            alert("You pressed the mouse at " + e.pageX + " " + e.pageY);

    Interesting events include click, mousemove, mouseup/down. You canuse all jQuery events. Usually, the event handlers will update thestate by drawing something (add a drawOverlay hook and calltriggerRedrawOverlay) or firing an externally visible event foruser code. See the crosshair plugin for an example.

    Currently, eventHolder actually contains both the static canvasused for the plot itself and the overlay canvas used forinteractive features because some versions of IE get the stackingorder wrong. The hook only gets one event, though (either for theoverlay or for the static canvas).

    Note that custom plot events generated by Flot are not generated oneventHolder, but on the div placeholder supplied as the firstargument to the plot call. You can get that withplot.getPlaceholder() - that's probably also the one you should useif you need to fire a custom event.

  • drawOverlay [phase 7]

    function (plot, canvascontext)

    The drawOverlay hook is used for interactive things that need acanvas to draw on. The model currently used by Flot works the waythat an extra overlay canvas is positioned on top of the staticcanvas. This overlay is cleared and then completely redrawnwhenever something interesting happens. This hook is called whenthe overlay canvas is to be redrawn.

    "canvascontext" is the 2D context of the overlay canvas. You canuse this to draw things. You'll most likely need some of themetrics computed by Flot, e.g. plot.width()/plot.height(). See thecrosshair plugin for an example.

  • shutdown [phase 8]

    function (plot, eventHolder)

    Run when plot.shutdown() is called, which usually only happens incase a plot is overwritten by a new plot. If you're writing aplugin that adds extra DOM elements or event handlers, you shouldadd a callback to clean up after you. Take a look at the section inPLUGINS.txt for more info.


Plugins extend the functionality of Flot. To use a plugin, simplyinclude its Javascript file after Flot in the HTML page.

If you're worried about download size/latency, you can concatenate allthe plugins you use, and Flot itself for that matter, into one big file(make sure you get the order right), then optionally run it through aJavascript minifier such as YUI Compressor.

Here's a brief explanation of how the plugin plumbings work:

Each plugin registers itself in the global array $.plot.plugins. Whenyou make a new plot object with $.plot, Flot goes through this arraycalling the "init" function of each plugin and merging default optionsfrom the "option" attribute of the plugin. The init function gets areference to the plot object created and uses this to register hooksand add new public methods if needed.

See the PLUGINS.txt file for details on how to write a plugin. As theabove description hints, it's actually pretty easy.

Version number

The version number of Flot is available in $.plot.version.

0 收藏
0 评论
0 收藏