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

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

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

这是我做的测试效果图。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>demo</title><link href="../examples/layout.css" rel="stylesheet" type="text/css"><!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]--><script language="javascript" type="text/javascript" src="../jquery.js"></script><script language="javascript" type="text/javascript" src="../jquery.flot.js"></script></head><body>
<div id="placeholder" style="width:600px;height:300px"></div><script type="text/javascript">
$(function () {var pl = $.plot($("#placeholder"), [//球员图片可以单独定义 或者和下面的日期一样 和每场数据合并在一起(这样好像有点浪费带宽){ label: "凯文-杜兰特", data: [[1,49,"热火vs湖人","05月01日"], [2,22,"热火vs雷霆","05月02日"], [3,36,"热火vs蛮牛","05月03日"],[4,27,"热火vs骑士","05月24日"],[5,39,"热火vs雷霆","05月25日"],[6,25,"热火vs蛮牛","05月26日"],[7,18,"热火vs湖人","05月27日"],[8,29,"热火vs骑士","05月28日"],[9,32,"热火vs剑客","05月29日"],[10,27,"热火vs测试","05月30日"]]},{ label: "麦克-詹姆斯", data: [[1,0,"冷锋vs雷霆","05月21日"],[2,0,"冷锋vs雷霆","05月22日"], [3,0,"冷锋vs雷霆","05月23日"],[4,37,"冷锋vs雷霆","05月24日"],[5,29,"冷锋vs雷霆","05月25日"],[6,21,"冷锋vs雷霆","05月26日"],[7,28,"冷锋vs雷霆","05月27日"],[8,19,"冷锋vs雷霆","05月28日"],[9,22,"冷锋vs雷霆","05月29日"],[10,29,"冷锋vs雷霆","05月30日"]]}],{series: {//控制线的填充、点的显示lines: { show: true},points: { show: true}},//开启鼠标移动和点击事件  折线图外框颜色 和 外框的宽度grid: { hoverable: true, clickable: true, borderColor:'#000',borderWidth:1},xaxis: {//x轴的最大最小范围 和 刻度自定义。min: 0,max: 22,ticks: [1,3,5,7,9,11,13,15,17,19,21]},yaxis: {//y轴的最小范围min: 0,// max: 50}});function showTooltip(x, y, contents) {//浮动块信息$('<div id="tooltip">' + contents + '</div>').css( {position: 'absolute',display: 'none',top: y + 5,left: x + 5,border: '1px solid #fdd',padding: '2px','background-color': '#fee',opacity: 0.80}).appendTo("body").fadeIn(200);}// function getData(data, x) {//  // alert(data);//   // x = x-1;//  return {data[x]['team'],data[x]['time']};// }var previousPoint = null;$("#placeholder").bind("plothover", function (event, pos, item) {if (item) {if (previousPoint != item.dataIndex) {previousPoint = item.dataIndex;$("#tooltip").remove();var x = item.datapoint[0],//x y 轴位置y = item.datapoint[1],n = x-1;// alert(item.series);//var data = pl.getData();var changci = item.series['data'][n][2],//场次信息 获取当前焦点的 数据信息 通过n(即x轴位置获取数据)shijian = item.series['data'][n][3];//同上 场次信息获取原理。 比赛时间// alert(changci);// alert(changci);//              for(i in item.series){//                   document.write('i:'+i+'   '+item.series[i]+'<hr>');// }var contents = "<img src='http://sports.sohu.com/upload/lakers/Kobe-Bryant.jpg' />比赛场次:"+changci+"<br />得分:"+y+"<br />比赛时间:"+shijian;showTooltip(item.pageX, item.pageY,contents);}}else {$("#tooltip").remove();previousPoint = null;            }});
});
</script></body>
</html>

=========================================下面转载flot的参数======================================

基本使用

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

?
1
2
3
<!--[ if  lte IE 8]><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
2
3
$( function  () {
     $.plot($( "#placeholder" ), [[[0, 0], [1, 2]]]);
});

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

数据格式

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

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

对象格式的数据,如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
     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
}

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

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

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

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

选项设置

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
{
   // 自定义数据系列
   series: {
     //共有属性:点、线、柱状图的显示方式
     lines, points, bars: {
           // 是否显示
           show: boolean
           // 线宽度
           lineWidth: number
           // 是否填充
           fill: boolean or number
           // 填充色,如rgba(255, 255, 255, 0.8)
           fillColor: null  or color/gradient
       }
       // 只针对点的属性
       points: {
           //点的半径
           radius: number
           // 绘制点的方法,默认为内置的圆形,可以通过自定义函数来定义其他形状
           symbol: "circle"  or function
       }
       // 只针对柱状图的属性
       bars: {
           barWidth: number
           align: "left" , "right"  or "center"
           horizontal: boolean
       }
       // 只针对线的属性
       lines: {
           // 指定两个点之间是用水平线还是垂直线连接
           steps: boolean
       }
       // 设置阴影的大小,0消除阴影
       shadowSize: number
       // 鼠标悬停时的颜色
       highlightColor: color or number
   }
   // 设置各个对应的数据序列,即线的颜色
   colors: [ color1, color2, ... ]
   // 网格设置
   grid: {
       // 是否显示格子
       show: boolean
       // 数据的线是否绘制在网格线下
       aboveData: boolean
       // 网格线颜色
       color: color
       // 网格背景颜色
       backgroundColor: color/gradient or null
       margin: number or margin object({top,left,bottom,right})
       // 刻度与网格间距
       labelMargin: number
       axisMargin: number
       markings: array of markings or (fn: axes -> array of markings)
       // 边框宽度
       borderWidth: number
       // 边框颜色
       borderColor: color or null
       minBorderMargin: number or null
       // 监听鼠标点击,会生成plotclick事件
       clickable: boolean
       // 监听鼠标移动,会生成plothover事件
       hoverable: boolean
       // 鼠标附近元素高亮显示
       autoHighlight: boolean
       mouseActiveRadius: number
   }
   interaction: {
       // 最大重绘延迟
       redrawOverlayInterval: number or -1
   }
   // x,y轴的设置
   xaxis, yaxis: {
       show: null  or true / false
       // 刻度文字显示的位置
       position: "bottom"  or "top"  or "left"  or "right"
       // 设置成time类型时可以用时间作为数据
       mode: null  or "time"  ( "time"  requires jquery.flot.time.js plugin)
       // 时区,仅用于time模式
       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
   }
   // 定义多个坐标轴
   xaxes: []
   yaxes: []
   // 图例
   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

?
1
2
3
4
5
       //图例的容器,用于从图表中分离
       container: null  or jQuery object/DOM element/jQuery expression
       sorted: null / false , true , "ascending" , "descending"  or a comparator
   }
}

格式化图例的显示

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

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

轴的设置

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
$.plot($( "#placeholder" ),
   [{ label: "Foo" , data: [[10, 1], [17, -14], [30, 5]] },
     { label: "Bar" , data: [[11, 13], [19, 11], [30, -7]] }
   ],
   {
     xaxis: {
       ticks: [0, 2, 4, 8, 10, 15],
       min: 0,
       max: 30
     }
   }
   );

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

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

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

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

绘制多个刻度轴

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

?
1
2
3
4
5
6
7
8
9
10
$.plot($( "#placeholder" ),
   [ { label: "Foo" , data: [[10, 1], [17, -14], [30, 5]] },
     { label: "Bar" , data: [[11, 13], [19, 11], [30, -7]] },
     { label: "Three" , data: [[2, 6], [5, 8], [18, 15]], yaxis: 2 },
   ],
   {
     xaxes: [{ position: "bottom"  }],
     yaxes: [{ position: "left"  }, { position: "right" , min: 2 }]
   }
   );

时间格式的数据

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%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)
%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)

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

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

使用如下:

?
1
2
3
4
5
6
7
8
9
10
11
$.plot($( "#placeholder" ),
    [{ label: "Foo" , data: [[ new  Date(2010, 1, 1), 1], [ new  Date(2010, 5, 1), -14], [ new  Date(2010, 10, 1), 5]] },
      { label: "Bar" , data: [[ new  Date(2010, 2, 1), 13], [ new  Date(2010, 6, 1), 11], [ new  Date(2010, 12, 1), -7]] }
    ],
    {
      xaxis: {
        mode: "time" ,
        timeformat: "%y/%m/%d"
      }
    }
    );

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

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

特殊的显示需求

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$.plot($( "#placeholder" ),
    [ { label: "Foo" , data: [[1, new  Date(2010, 1, 1)], [2, new  Date(2010, 5, 1)], [3, new  Date(2010, 10, 1)]] },
      { label: "Bar" , data: [[1, new  Date(2010, 2, 1)], [2, new  Date(2010, 6, 1)], [3, new  Date(2010, 12, 1)]] }
    ],
    {
      yaxis: {
        mode: "time" ,
        timeformat: "%y/%m/%d"
      },
      xaxis: {
        ticks: [[1, "一" ], [2, "二" ], [3, "三" ]]
      }
    }
    );

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

控制线和点的显示

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

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

颜色的控制

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

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

再比如网格的背景色:

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

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

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

跟踪鼠标事件

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

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

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

?
1
2
3
4
5
6
7
8
9
10
$( "#placeholder" ).bind( "plotclick" , function  (event, pos, item) {
   console.log( "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) {
     console.log(item.series, item.datapoint);
     console.log( "You clicked a point!" );
   }
});

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

?
1
2
3
4
5
6
7
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
}

内置方法

  • 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
2
3
4
5
6
7
var  pl = $.plot($( "#placeholder" ), data, options);
  $( "#placeholder" ).bind( "plotclick" , function  (event, pos, item) {
    if  (item) {
      pl.highlight(item.series, item.datapoint);
    }
  });

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

相关资源

插件主页:http://code.google.com/p/flot/   (API文档:http://people.iola.dk/olau/flot/API.txt)

最新版本:https://github.com/flot/flot  (API文档:https://github.com/flot/flot/blob/master/API.md)

在线DEMO:http://people.iola.dk/olau/flot/examples/

Flot的插件:http://code.google.com/p/flot/wiki/Plugins (实现更多类型的图表)

【部分原创】jquery图表插件flot笔记相关推荐

  1. jQuery图表插件Flot

    最近正在使用JQuery的flot进行画图,但是这方面的中文帮助实在是太少了,干脆把英文的document直接翻译一下吧.因为也是再学习过程当中,难免会存在翻译不准确的地方,如果文中描述的不明白的话, ...

  2. JQuery图表插件Flot之属性方法

    更多详情:http://www.cnblogs.com/jirimutu01/archive/2011/07/13/2105150.html 中文详解:http://www.cnblogs.com/q ...

  3. 6款jQuery图表插件

    图表应用能让数据显示更加直观易懂,但光靠CSS +Xhtml 或纯图片实现的图表显然有很多局限性,强大的jquery 让我们可以实现各种很强大的图表,下面是6款jQuery图表插件 ,另外,你也许也愿 ...

  4. JQuery图表插件Highcharts示例教程

    JQuery图表插件Highcharts示例教程,先上图,大伙Show一下效果:先上三个图,分别是曲线.柱状.扇形. 图表中的数据纯属于DEMO的测试数据,没有实际用意.下面讲下大致的实现步骤 第一步 ...

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

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

  6. jQuery 图表插件 jqChart 使用

    jQuery 图表插件 jqChart显示效果效果非常好.支持以下几种图表: Area Bar Bubble Column Financial Chart - Candlestick Financia ...

  7. JQuery图表插件之Flot

    Flot是一个Jquery下图表插件,具有简单使用,交互效果,具有吸引力外观特点.目前支持 Internet Explorer 6+, Chrome, Firefox 2+, Safari 3+ an ...

  8. flot - jQuery 图表插件(jquery.flot)使用

    Flot是纯Javascript实现的基于jQuery的图表插件,主要支持线状图和柱状图的绘制(通过插件也可以支持饼状图). 它的特点是使用简单.图形美观,支持鼠标跟踪及缩放功能. Flot是基于ca ...

  9. flot - jQuery 图表插件(jquery.flot)使用-2

    Flot是纯Javascript实现的基于jQuery的图表插件,主要支持线状图和柱状图的绘制(通过插件也可以支持饼状图). 它的特点是使用简单.图形美观,支持鼠标跟踪及缩放功能. Flot是基于ca ...

最新文章

  1. jdk8新特性_JDK8与JDK9新特性学习
  2. 台式您想使用系统还原计算机吗,联想台式机一键恢复,小编教你怎么使用联想电脑一键恢复...
  3. [转]TensorFlow如何进行时序预测
  4. linux shell 计算器 除0,用shell写一个简易计算器,可以实现加、减、乘、除运算,假如脚本名字为1.sh,执行示例:./1....
  5. Repeating Cipher
  6. 36 张图梳理 Intellij IDEA 常用设置,太全了值得收藏!
  7. 局域网即时通讯的可管理性
  8. 初学shell,今天遇到由wget下载到本地的网页源代码的乱码问题,无聊的写了一个转码的脚本...
  9. 解决:fatal: not a git repository (or any of the parent directories): .git的问题
  10. 百度云强势入围 2018 Q3 Forrester Wave,仅用两年成为公有云一方霸主
  11. 【OpenCV入门指南】第四篇 图像的二值化
  12. FPGA笔记(八)-驱动12864
  13. android 蓝牙串口指令,蓝牙串口助手
  14. opencv图片显示到mfc控件中,按键打开
  15. 多边形的扫描转换算法 c语言,C++程序例题:多边形扫描转换算法
  16. 做项目的一些心得体会
  17. 【Android学习之路】之从零开始做一个小项目(一)
  18. Linux内核4.14版本:ARM64的内核启动过程(二)——start_kernel
  19. 微信小程序开发--组织通讯录
  20. pytorch官网预训练模型百度云下载 VGG16,Densnet169,inception_v3

热门文章

  1. 模拟经营动物园java,动物园游戏下载|动物园下载 (经典模拟经营游戏)_单机游戏下载...
  2. 平衡车之转向环分析及调试
  3. 表单时间转换器(formatDate)
  4. Flex 布局 justify-content:right不生效
  5. 今天在Palm上读完钱穆的《中国历代政治得失》
  6. java 单例 dcl_java 中单例模式DCL的缺陷及单例的正确写法
  7. C语言中的void类型函数
  8. Doris Routine Load正则表达实战
  9. html移除disabled属性,使用jQuery设置disabled属性与移除disabled属性
  10. dell计算机电源开关按钮,DELL电源适配器的按钮开关定个位