管理画面などに格好いいグラフがあるとテンションがあがりますよね。とは言えグラフを表示するというのは意外と面倒で、ついつい後回しになってしまいがちです。 そこで手軽に格好いいグラフを描けるライブラリとしてmorris.jsを紹介します。

morris.jsの使い方

morris.jsはまずJavaScript/スタイルシートを読み込みます。

<link rel="stylesheet" href="http://cdn.oesmith.co.uk/morris-0.4.3.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="http://cdn.oesmith.co.uk/morris-0.4.3.min.js"></script>

次に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']
});

できあがるグラフはSVGで、マウスの動きに連動します。

できたグラフ。滑らかな曲線を描いています。

morris.jsの例

折れ線グラフ。

棒グラフ。

円グラフ。

積み上げグラフ。

これらのグラフを手軽に描く際に使ってみる良さそうです。SVGとあって、スマートフォンでも描けますし、拡大しても綺麗なのがメリットですね。

morris.jsはJavaScript製、BSD Licenseのオープンソース・ソフトウェアです。

morris.js morrisjs/morris.js