天天看點

Javascript FLOT畫圖插件詳解 基本使用 資料格式 選項設定 内置方法

Flot是純Javascript實作的基于jQuery的圖表插件,主要支援線狀圖和柱狀圖的繪制(通過插件也可以支援餅狀圖)。

它的特點是使用簡單、圖形美觀,支援滑鼠跟蹤及縮放功能。

Flot是基于canvas進行圖表的繪制,可以在IE6+/Firefox2+/Safari3+/Opera9.5+/Chrome等主流浏覽器上運作;其中IE9以下浏覽器不支援canvas标記,需要額外引用excanvas庫(VML)來實作。

Javascript FLOT畫圖插件詳解 基本使用 資料格式 選項設定 内置方法

這是我做的測試效果圖。

[html]  view plain copy

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html>  
  3.  <head>  
  4.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  5.     <title>demo</title>  
  6.     <link href="../examples/layout.css" rel="stylesheet" type="text/css">  
  7.     <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->  
  8.     <script language="javascript" type="text/javascript" src="../jquery.js"></script>  
  9.     <script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>  
  10.  </head>  
  11.  <body>  
  12. <div id="placeholder" style="width:600px;height:300px"></div>  
  13. <script type="text/javascript">  
  14. $(function () {  
  15.     var pl = $.plot($("#placeholder"),   
  16.   [//球員圖檔可以單獨定義 或者和下面的日期一樣 和每場資料合并在一起(這樣好像有點浪費帶寬)  
  17.    { 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日"]]},  
  18.        { 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日"]]}  
  19.   ],  
  20.   {  
  21.     series: {//控制線的填充、點的顯示  
  22.       lines: { show: true},  
  23.       points: { show: true}  
  24.     },  
  25.     //開啟滑鼠移動和點選事件  折線圖外框顔色 和 外框的寬度  
  26.     grid: { hoverable: true, clickable: true, borderColor:'#000',borderWidth:1},  
  27.     xaxis: {//x軸的最大最小範圍 和 刻度自定義。  
  28.       min: 0,  
  29.       max: 22,  
  30.       ticks: [1,3,5,7,9,11,13,15,17,19,21]  
  31.     },  
  32.     yaxis: {//y軸的最小範圍  
  33.       min: 0,  
  34.       // max: 50  
  35.     }  
  36.   }  
  37.   );  
  38.     function showTooltip(x, y, contents) {//浮動塊資訊  
  39.         $('<div id="tooltip">' + contents + '</div>').css( {  
  40.             position: 'absolute',  
  41.             display: 'none',  
  42.             top: y + 5,  
  43.             left: x + 5,  
  44.             border: '1px solid #fdd',  
  45.             padding: '2px',  
  46.             'background-color': '#fee',  
  47.             opacity: 0.80  
  48.         }).appendTo("body").fadeIn(200);  
  49.     }  
  50.     // function getData(data, x) {  
  51.     //  // alert(data);  
  52.     //  // x = x-1;  
  53.     //  return {data[x]['team'],data[x]['time']};  
  54.     // }  
  55.     var previousPoint = null;  
  56.     $("#placeholder").bind("plothover", function (event, pos, item) {  
  57.       if (item) {  
  58.           if (previousPoint != item.dataIndex) {  
  59.               previousPoint = item.dataIndex;  
  60.               $("#tooltip").remove();  
  61.               var x = item.datapoint[0],//x y 軸位置  
  62.                   y = item.datapoint[1],  
  63.                   n = x-1;  
  64.                   // alert(item.series);  
  65.                   //var data = pl.getData();  
  66.                   var changci = item.series['data'][n][2],//場次資訊 擷取目前焦點的 資料資訊 通過n(即x軸位置擷取資料)  
  67.                       shijian = item.series['data'][n][3];//同上 場次資訊擷取原理。 比賽時間  
  68.                       // alert(changci);  
  69.                   // alert(changci);  
  70.      //              for(i in item.series){  
  71.                     //                      document.write('i:'+i+'   '+item.series[i]+'<hr>');  
  72.                     // }  
  73.               var contents = "<img src='http://sports.sohu.com/upload/lakers/Kobe-Bryant.jpg' />比賽場次:"+changci+"<br />得分:"+y+"<br />比賽時間:"+shijian;  
  74.               showTooltip(item.pageX, item.pageY,contents);  
  75.           }  
  76.       }  
  77.       else {  
  78.           $("#tooltip").remove();  
  79.           previousPoint = null;              
  80.       }  
  81.     });  
  82. });  
  83. </script>  
  84.  </body>  
  85. </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還提供了一些函數,用于在繪圖各個流程步驟中進行一些額外的處理,這裡不再列出。

繼續閱讀