• flot


    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="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还提供了一些函数,用于在绘图各个流程步骤中进行一些额外的处理,这里不再列出。

  • 相关阅读:
    素数判定方法,方法持续更新...
    C++暂停黑窗口
    【python爬虫】scrapy入门6-生成多个spider
    【python爬虫】scrapy入门5--xpath等后面接正则
    python基础:list与string互转
    【python爬虫】scrapy实战1--百万微博任性采集
    【python爬虫】scrapy入门4--添加cookies
    【python爬虫】scrapy入门2--自定义item
    【python爬虫】scrapy入门1--环境搭建
    sklearn学习:为什么roc_auc_score()和auc()有不同的结果?
  • 原文地址:https://www.cnblogs.com/qing123/p/4531710.html
Copyright © 2020-2023  润新知