Morris.js 是基于 jQuery 和 Raphaël 的轻量级矢量图形库,帮助开发人员轻松绘制各种形式的图表。示例:
HTML:
<div id="myfirstchart" style="height: 250px;"></div>
JavaScript:
new Morris.Line({ // ID of the element in which to draw the chart. element: 'myfirstchart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: [ { year: '2008', value: 20 }, { year: '2009', value: 10 }, { year: '2010', value: 5 }, { year: '2011', value: 5 }, { year: '2012', value: 20 } ], // The name of the data record attribute that contains x-values. xkey: 'year', // A list of names of data record attributes that contain y-values. ykeys: ['value'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Value'] });
依赖类库:
- jQuery >=1.7
- Raphaël >=2.0
支持浏览器:
- IE6+
- Safari/Chrome/Firefox
- iOS 3+
- Android 3+
如何使用?
morris.js的使用很简单,你只需要使用一个方法:
Morris.Line(options)
选项:
- element(必选): 用来插入图形的元素 (注意:这个元素必须宽度和高度定义在自己的样式表里)
- data(必选):用来绘图的数据,可以使对象数组,包含了x和y轴属性(注意:排序在这里不重要,你可以按你的需要随意的排序)
- xkey (必选):包含了X轴属性名字,支持如下格式:2012, 2012 Q1, 2012-02, 2012-02-24.
- ykeys (必选):一个包含Y值的属性名称,每一个对应一个绘制的数据
- labels (必选): 一个包含数据序列名称的标识(对应ykeys选项的值)
- lineWidth (可选): 序列线宽度
- pointSize (可选): 序列点直径
- lineColors (可选): 序列线/点的颜色数组
- ymax (可选): Y数值的最大值,或者你可以设置为"auto"或者"auto[数值]",保证最小必须为指定数值
- smooth (可选): false则禁止光滑处理
代码:
// annual data Morris.Line({ element: 'annual', data: [ {y: '2012', a: 100}, {y: '2011', a: 75}, {y: '2010', a: 50}, {y: '2009', a: 75}, {y: '2008', a: 50}, {y: '2007', a: 75}, {y: '2006', a: 100} ], xkey: 'y', ykeys: ['a'], labels: ['Series A'] });
研究下面的例子:
Morris.Bar({ element: 'bar-example', data: [ { y: '2006', a: 100, b: 90 }, { y: '2007', a: 75, b: 65 }, { y: '2008', a: 50, b: 40 }, { y: '2009', a: 75, b: 65 }, { y: '2010', a: 50, b: 40 }, { y: '2011', a: 75, b: 65 }, { y: '2012', a: 100, b: 90 } ], xkey: 'y', ykeys: ['a', 'b'], labels: ['Series A', 'Series B'] });
ykeys可以有多个值,而每个值对应labels的名称!