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

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

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

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

基本使用

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

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 (实现更多类型的图表)

 

参考:http://www.codexy.cn/jquery/jquery-tutorial.html

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值