jQuery.Flot开发手记

介绍

项目地址:http://www.flotcharts.org/
API文档:https://github.com/flot/flot/blob/master/API.md

Flots是基于jQuery的纯JavaScript图标绘制类库,专注于简单实用,美观,交互。

使用

1、引用JS

<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>

2、html中声明要显示图表的div

<div id="placeholder" class="demo-placeholder"></div>

3、初始化数据

<script type="text/javascript">
 
    $(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]];
 
        //数据中使用null,可以中断该数据线条
 
        var d3 = [[0, 12], [7, 12], null, [7, 2.5], [12, 2.5]];
 
        $.plot("#placeholder", [ d1, d2, d3 ]);
 
        // Add the Flot version string to the footer
 
        $("#footer").prepend("Flot " + $.plot.version + " &ndash; ");
    });
 
    </script>

3、Flot已经为我们自动生成图表

自定义参数

var options = {
    series: {
        lines: { show: true },
        points: { show: true }
    }
};
$.plot(placeholder, data, options);

自定义图例

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
}

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

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

自定义坐标

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//canvas坐标转数据坐标会调用
 
    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
}

//文字可以直接设置成如下格式
font:{
    size: 11,
    lineHeight: 13,
    style: "italic",
    weight: "bold",
    family: "sans-serif",
    variant: "small-caps",
    color: "#545454"
}
//可以指定坐标刻度的显示位置和显示文字
ticks: [[0, "zero"], [1.2, "one mark"], [2.4, "two marks"]]

//可以直接以时间作为刻度
xaxis: {
    mode: "time",
    timeformat: "%Y/%m/%d"
}

%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)
//可以自定义日期月份名称
monthNames: ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]
dayNames: ["dim", "lun", "mar", "mer", "jeu", "ven", "sam"]
//可以完全自定义
tickFormatter: function (val, axis) {
    var d = new Date(val);
    return d.getUTCDate() + "/" + (d.getUTCMonth() + 1);
}

自定义数据序列

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, ... ]

//自定义链接
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);
}

自定义网格

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
}

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

//画线
markings: [ { xaxis: { from: 0, to: 2 }, yaxis: { from: 10, to: 10 }, color: "#bb0000" }, ... ]
//画矩形
markings: [ { yaxis: { from: 1, to: 1 } }, ... ]
//完全自定义
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;
}

//响应点击事件 "plotclick"或"plothover"
$.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!");
    }
});
//item对象格式如下
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
}

其他

鼠标停留在图表节点时显示tooltip


$("#chart").bind("plothover",
function(event, pos, item) {
$("#x").text(pos.x);
$("#y").text(pos.y);

if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;

$("#tooltip").remove();
var x = item.datapoint[0],
y = item.datapoint[1];
var newDate = new Date();
newDate.setTime(x);
var x_value = newDate.toLocaleDateString();
if ((x + "").length < 3)
x_value = x + ":00";
showTooltip(item.pageX, item.pageY,
item.series.label + "(" + x_value + "):" + y);
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});

function showTooltip(x, y, contents) {
    $('<div id="tooltip">' + contents + '</div>').css({
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 15,
        border: '1px solid #333',
        padding: '4px',
        color: '#fff',
        'border-radius': '3px',
        'background-color': '#333',
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}
posted @ 2016-02-23 01:03  leestar54  阅读(667)  评论(0编辑  收藏  举报