Flot是纯Javascript实现的基于jQuery的图表插件,主要支持线状图和柱状图的绘制(通过插件也可以支持饼状图)。

特别注意Flot使用的是UTC时间,最好修改flot.js去掉所有的UTC

它的特点是使用简单、图形美观,支持鼠标跟踪及缩放功能。

Flot是基于canvas进行图表的绘制,可以在IE6+/Firefox2+/Safari3+/Opera9.5+/Chrome等主流浏览器上运行;其中IE9以下浏览器不支持canvas标记,需要额外引用excanvas库(VML)来实现。

基本使用

首先,在页面头部引用脚本:

<!--[if IE]><script src="js/excanvas.min.js"></script><![endif]-->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.flot.min.js"></script>
 
 
 

在页面中创建一个html标记,如div,然后通过样式来指定图表的大小:

1 <div id="placeholder" style="width:600px;height:300px;"></div>
 

最后,在DOM Ready事件中调用Flot的绘制方法$.plot:

1 $(function () {
2     $.plot($("#placeholder"), [[[0, 0], [1, 2]]]);
3 });
 

这样就简单的绘制了一条线。

数据格式

flot的数据格式是数组,数组中包含多个系列的数据,每个系列的数据对应一条线:

1 [ series1, series2, ... ]
 
 

每一个系列的数据可以是一个数组或者对象。

数组格式的数据,每一个点都是一个数组(分x/y轴):

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

如下定义了三个点:

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

绘制图表的时候,会把这三个点连接起来;假如中间有个点使用了空值即null,这个点的两边则不会连接起来:

1 [ [1, 3], [2, 14.01], null, [3.5, 3.14], [5, 8] ]
 

需要注意的是,每个点的数据必须是数字,如果是字符串,可能会得到奇怪的错误。

对象格式的数据,如下:

01 {
02     color: color or number  //颜色,如果不设置会自动生成
03     data: rawdata //数据
04     label: string //用于图例说明
05     lines: specific lines options
06     bars: specific bars options
07     points: specific points options
08     xaxis: number
09     yaxis: number
10     clickable: boolean
11     hoverable: boolean
12     shadowSize: number
13     highlightColor: color or number
14 }
 

通常不需要关心其他选项,只需要指定label和data:

1 {
2     label: "y = 3",
3     data: [[0, 3], [10, 3]]
4 }

对象格式的数据提供更大的灵活性,也更有利于代码的可读性,如下定义了两个系列即两条线:

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

选项设置

所有的选项都是可选的,改变某个属性,只需要指定特定的属性名称:

001 {
002   // 自定义数据系列
003   series: {
004     //共有属性:点、线、柱状图的显示方式
005     lines, points, bars: {
006           // 是否显示
007           show: boolean
008           // 线宽度
009           lineWidth: number
010           // 是否填充
011           fill: boolean or number
012           // 填充色,如rgba(255, 255, 255, 0.8)
013           fillColor: null or color/gradient
014       }
015       // 只针对点的属性
016       points: {
017           //点的半径
018           radius: number
019           // 绘制点的方法,默认为内置的圆形,可以通过自定义函数来定义其他形状
020           symbol: "circle" or function
021       }
022       // 只针对柱状图的属性
023       bars: {
024           barWidth: number
025           align: "left", "right" or "center"
026           horizontal: boolean
027       }
028       // 只针对线的属性
029       lines: {
030           // 指定两个点之间是用水平线还是垂直线连接
031           steps: boolean
032       }
033       // 设置阴影的大小,0消除阴影
034       shadowSize: number
035       // 鼠标悬停时的颜色
036       highlightColor: color or number
037   }
038   // 设置各个对应的数据序列,即线的颜色
039   colors: [ color1, color2, ... ]
040   // 网格设置
041   grid: {
042       // 是否显示格子
043       show: boolean
044       // 数据的线是否绘制在网格线下
045       aboveData: boolean
046       // 网格线颜色
047       color: color
048       // 网格背景颜色
049       backgroundColor: color/gradient or null
050       margin: number or margin object({top,left,bottom,right})
051       // 刻度与网格间距
052       labelMargin: number
053       axisMargin: number
054       markings: array of markings or (fn: axes -> array of markings)
055       // 边框宽度
056       borderWidth: number
057       // 边框颜色
058       borderColor: color or null
059       minBorderMargin: number or null
060       // 监听鼠标点击,会生成plotclick事件
061       clickable: boolean
062       // 监听鼠标移动,会生成plothover事件
063       hoverable: boolean
064       // 鼠标附近元素高亮显示
065       autoHighlight: boolean
066       mouseActiveRadius: number
067   }
068  
069   interaction: {
070       // 最大重绘延迟
071       redrawOverlayInterval: number or -1
072   }
073   // x,y轴的设置
074   xaxis, yaxis: {
075       show: null or true/false
076       // 刻度文字显示的位置
077       position: "bottom" or "top" or "left" or "right"
078       // 设置成time类型时可以用时间作为数据
079       mode: null or "time" ("time" requires jquery.flot.time.js plugin)
080       // 时区,仅用于time模式
081       timezone: null, "browser" or timezone (only makes sense for mode: "time")
082       // 轴文字和刻度文字颜色
083       color: null or color spec
084       // 单独定义刻度文字颜色
085       tickColor: null or color spec
086       font: null or font spec object
087       // 最大最小只范围,不设置则自动计算
088       min: null or number
089       max: null or number
090       autoscaleMargin: null or number
091       // 对数据进行计算后再绘制
092       transform: null or fn: number -> number
093       inverseTransform: null or fn: number -> number
094       // 用于自定义刻度显示
095       ticks: null or number or ticks array or (fn: axis -> ticks array)
096       tickSize: number or array
097       minTickSize: number or array
098       // 格式化刻度显示
099       tickFormatter: (fn: number, object -> string) or string
100       // 刻度显示精确度,即小数位数
101       tickDecimals: null or number
102       // 刻度区域大小
103       labelWidth: null or number
104       labelHeight: null or number
105       reserveSpace: null or true
106  
107       tickLength: null or number
108  
109       alignTicksWithAxis: null or number
110   }
111   // 定义多个坐标轴
112   xaxes: []
113   yaxes: []
114   // 图例
115   legend: {
116       show: boolean
117       // 格式化图例的显示
118       labelFormatter: null or (fn: string, series object -> string)
119       labelBoxBorderColor: color
120       noColumns: number
121       position: "ne" or "nw" or "se" or "sw"
122       margin: number of pixels or [x margin, y margin]
123       backgroundColor: null or color
124       backgroundOpacity: number between 0 and 1
125 //图例的容器,用于从图表中分离
126       container: null or jQuery object/DOM element/jQuery expression
127       sorted: null/false, true, "ascending", "descending" or a comparator
128        }
129       }

格式化图例的显示

通过legend参数的labelFormatter参数来格式化图例的显示,其中series为一个对象(属性参考对象格式的数据):

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

轴的设置

自定义刻度的显示,可以通过ticks参数来设置,如下定义X轴:

1 xaxis: {
2   ticks: [0, 2, 4, 8, 10, 15]
3 }

这样轴上只会显示以上定义的刻度。当有时候数据超出这个范围时,部分刻度会被隐藏,这时候就需要手动指定min/max参数,如下:

01 $.plot($("#placeholder"),
02   [{ label: "Foo", data: [[10, 1], [17, -14], [30, 5]] },
03     { label: "Bar", data: [[11, 13], [19, 11], [30, -7]] }
04   ],
05   {
06     xaxis: {
07       ticks: [0, 2, 4, 8, 10, 15],
08       min: 0,
09       max: 30
10     }
11   }
12   );
 

ticks参数还可以定制刻度显示的文字:

1 ticks: [[0, "零"], [2, "二"], [4, "四"], [8, "八"], [10, "十"], [15, "十五"]]
 

最强大的还是通过自定义函数,通过tickFormatter参数:

1 tickFormatter: function(axis) {
2   return "数字" + axis.toString();
3 }

绘制多个刻度轴

如下,绘制两个y轴,同时需要在数据中指定属于哪个轴:

01 $.plot($("#placeholder"),
02   [ { label: "Foo", data: [[10, 1], [17, -14], [30, 5]] },
03     { label: "Bar", data: [[11, 13], [19, 11], [30, -7]] },
04     { label: "Three", data: [[2, 6], [5, 8], [18, 15]], yaxis: 2 },
05   ],
06   {
07     xaxes: [{ position: "bottom" }],
08     yaxes: [{ position: "left" }, { position: "right", min: 2 }]
09   }
10   );

时间格式的数据

使用时间格式的数据需要引用jquery.flot.time.js,它支持以下格式的时间格式化:

01 %a: weekday name (customizable)
02 %b: month name (customizable)
03 %d: day of month, zero-padded (01-31)
04 %e: day of month, space-padded ( 1-31)
05 %H: hours, 24-hour time, zero-padded (00-23)
06 %I: hours, 12-hour time, zero-padded (01-12)
07 %m: month, zero-padded (01-12)
08 %M: minutes, zero-padded (00-59)
09 %S: seconds, zero-padded (00-59)
10 %y: year (two digits)
11 %Y: year (four digits)
12 %p: am/pm
13 %P: AM/PM (uppercase version of %p)
14 %w: weekday as number (0-6, 0 being Sunday)

还支持自定义月份、一周中每一天的名称:

1 monthNames: ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]
2 dayNames: ["dim", "lun", "mar", "mer", "jeu", "ven", "sam"]

使用如下:

01 $.plot($("#placeholder"),
02    [{ label: "Foo", data: [[new Date(2010, 1, 1), 1], [new Date(2010, 5, 1), -14], [new Date(2010, 10, 1), 5]] },
03      { label: "Bar", data: [[new Date(2010, 2, 1), 13], [new Date(2010, 6, 1), 11], [new Date(2010, 12, 1), -7]] }
04    ],
05    {
06      xaxis: {
07        mode: "time",
08        timeformat: "%y/%m/%d"
09      }
10    }
11    );

当然,如果不使用timeformat的话,也可以用tickFormatter来格式化显示:

1 tickFormatter: function (val, axis) {
2   var d = new Date(val);
3   console.log(val)
4   return (d.getUTCMonth() + 1) + "/" + d.getUTCDate() + "/" + d.getFullYear();
5 }

特殊的显示需求

可能需要在同一个点上进行时间的对比,比如x轴:

01 $.plot($("#placeholder"),
02    [ { label: "Foo", data: [[1, new Date(2010, 1, 1)], [2, new Date(2010, 5, 1)], [3, new Date(2010, 10, 1)]] },
03      { label: "Bar", data: [[1, new Date(2010, 2, 1)], [2, new Date(2010, 6, 1)], [3, new Date(2010, 12, 1)]] }
04    ],
05    {
06      yaxis: {
07        mode: "time",
08        timeformat: "%y/%m/%d"
09      },
10      xaxis: {
11        ticks: [[1, "一"], [2, "二"], [3, "三"]]
12      }
13    }
14    );
 
 

在以上方法中,把x轴和x轴刻度的值一一对应,当然也可以换成y轴。

控制线和点的显示

通过series参数,可以控制线的填充、点的显示(点默认是不显示的):

1 series: {
2   lines: { show: true, fill:true },
3   points: { show: true, fill: false }
4 }

颜色的控制

flot有多个参数都用到了颜色,均可以通过定义单个、或多个颜色来控制每个数据呈现的颜色:

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

再比如网格的背景色:

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

颜色还有更加详细的选项来定义:

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

跟踪鼠标事件

主要有鼠标移动和点击事件,需要先开启相应开关:

1 grid: {
2   clickable: true,
3   hoverable: true
4 }
 

然后再绑定相应的事件,如点击事件:

01 $("#placeholder").bind("plotclick", function (event, pos, item) {
02   console.log("You clicked at " + pos.x + ", " + pos.y);
03   // axis coordinates for other axes, if present, are in pos.x2, pos.x3, ...
04   // if you need global screen coordinates, they are pos.pageX, pos.pageY
05  
06   if (item) {
07     console.log(item.series, item.datapoint);
08     console.log("You clicked a point!");
09   }
10 });

plothover事件的的绑定也一样。item对象主要有以下属性:

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

内置方法

  • highlight(series, datapoint):高亮显示point
  • unhighlight(series, datapoint) or unhighlight():取消高亮point,没有参数则取消高亮当前的point
  • setData(data):重新设置数据,需要调用draw()方法来重绘
  • setupGrid():重新计算坐标、轴,需要调用draw()方法来重绘
  • draw():重绘图表
  • triggerRedrawOverlay():更新可交互的区域,如point
  • width()/height():获取宽高
  • offset():获取偏移
  • pointOffset({ x: xpos, y: ypos }):获取某个点相对于placeholder的div的偏移
  • resize():调整图表的大小
  • shutdown():清理即取消绑定所有事件处理函数

还有一些其他函数,但需要你比较了解flot内部运作,否则可能产生不好的结果:

  • getData():获取数据,即在$.plot方法中定义的数据
  • getAxes():获取坐标轴
  • getPlaceholder():获取placeholder元素
  • getCanvas():获取canvas对象
  • getPlotOffset():获取偏移
  • getOptions():获取设置的选项

如highlight方法,就可以在click事件中使用:

1 var pl = $.plot($("#placeholder"), data, options);
2  
3  $("#placeholder").bind("plotclick", function (event, pos, item) {
4    if (item) {
5      pl.highlight(item.series, item.datapoint);
6    }
7  });
 

flot还提供了一些函数,用于在绘图各个流程步骤中进行一些额外的处理,这里不再列出。

flot - jQuery 图表插件(jquery.flot)使用的更多相关文章

  1. 不错的jQuery图表插件 .

    很多时候我们需要在网页中显示数据统计报表,从而能很直观地了解数据的走向,更好地帮助决策分析.今天就给大家分享几个个人觉得好用的jQuery图表插件,这几个图表插件使用起来非常方便,而且挺灵活的,相信大 ...

  2. 一款可定制的外国jQuery图表插件jqplot

    jqPlot是一个jQuery绘图插件,可以利用它制作漂亮的线状图和柱状图.jqPlot支持为图表设置各种不同的样式.提供Tooltips,数据点高亮显示等功能. 用法: 1.引入jQuery类库和相 ...

  3. 实时更新数据的jQuery图表插件DEMO演示

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. jQuery滚动条插件 – jquery.slimscroll.js

    jquery.slimscroll.js插件是一个支持把内容放在一个盒子里面,固定一个高度,超出的则使用滚动.jquery.slimscroll.js不仅可以定义高度.宽度,还可以定义位置.滚动条大小 ...

  5. Jquery 分页插件 Jquery Pagination

    Jquery 分页插件 Jquery Pagination 分页插件来说,我觉得适用就行,尽量简单然后能够根据不同的应用场景能够换肤.展现形式等. 对于初学者想写分页插件的同学,也可以看下源码,代码也 ...

  6. jQuery分页插件(jquery.page.js)的使用

    效果描述: 不用分页即可显示的jQuery插件 jQuery分页插件——jQuery.page.js用法很简单,效果很棒   1.前端   首先html的head中引入相关css与js <lin ...

  7. jQuery图表插件Flot中文文档

    转载自:http://www.itivy.com/ivy/archive/2011/6/4/jquery-flot-chinese-doc.html 最近正在使用JQuery的flot进行画图,但是这 ...

  8. python 全栈开发,Day58(bootstrap组件,bootstrap JavaScript 插件,后台模板,图表插件,jQuery插件库,Animate.css,swiper,运行vue项目)

    一.bootstrap组件 无数可复用的组件,包括字体图标.下拉菜单.导航.警告框.弹出框等更多功能. 组件和插件的区别? 插件:一个功能,比如js文件 组件:html css js 组件包含插件 面 ...

  9. JQuery多媒体插件jQuery Media Plugin使用详解

    malsup jquery media plugin 该插件可以播放多种类型的多媒体文件包括:Flash, Quicktime, Windows Media Player, Real Player, ...

随机推荐

  1. iOS中关于NavigationController中preferredStatusBarStyle一直不执行的问题

    重点:真的能改吗?跑起来毛用没有. 1.还要在plist文件里把View controller-based status bar appearance设置成YES. 2.一定要写UINavigatio ...

  2. Received an invalid response. Origin 'null' is therefore not allowed access

    Received an invalid response. Origin 'null' is therefore not allowed access. 今天在做二级联动,使用ajax请求xml数据, ...

  3. button按钮

    button按钮只加类名不加type时,点击此按钮页面会刷新

  4. js实现判断大写锁定是否开启(转)

    转载地址:http://www.cnblogs.com/xiaoao808/archive/2008/07/31/1257624.html 在用户登录输入密码时,常常会有因为大写锁定开启而造成输入密码 ...

  5. Redis到底该如何利用(二)?

    上一篇文章里我简述了使用Keys作为Redis搜索的方式,确实感受到了社区的力量,写文章好处多.首先谢谢各位前辈的指导,我知道了拿Redis作为搜索是个错误的方向.本来这篇文章我觉得确实没必要发了,但 ...

  6. GO语言中json与map的转换

    直接上代码(需要引入encoding/json包) // 当前程序的包名 package main // 导入其它的包 import ( "encoding/json" " ...

  7. 微信扫描打开APP下载链接提示代码优化(转)

    上一次我发了一篇文章叫“微信打开网址添加在浏览器中打开提示”,里面我发出来了三个代码,分别是纯JS.js+html.jQuery+HTML代码.今天来一个简化版带可以关闭的按钮操作.使用的是纯JS+H ...

  8. 数据的平面拟合 Plane Fitting

    数据的平面拟合 Plane Fitting 看到了一些利用Matlab的平面拟合程序 http://www.ilovematlab.cn/thread-220252-1-1.html

  9. 分享Kali Linux 2016.2第50周虚拟机

    分享Kali Linux 2016.2第50周虚拟机该虚拟机使用Kali Linux 2016.2第50周的64位镜像安装而成.基本配置如下:(1)该系统默认设置单CPU双核,内存为2GB,硬盘为50 ...

  10. [SDOI2013]方程

    ...最近考了一道数学题.是典型的隔板问题. P.S.最近八中oj上面没有系统地刷过题 题面可以直接转化为m个球分到n个箱子,每个箱子至少放1个,前n1个箱子的球数必须满足全部小于等于A[i],接着n ...