南国スキーぶろぐ・Z

岩手県盛岡市のネタを中心としたお出掛け雑記ブログ

当サイトはアフィリエイト広告を利用しております

岩手県と盛岡市のブログです

jQueryでグラフを作成出来る「CanvasJS」

にほんブログ村 地域生活(街) 東北ブログ 岩手県情報へ にほんブログ村 地域生活(街) 東北ブログ 盛岡市情報へ

2017/01/12

Web , ,

お仕事でグラフを画像ではなくテキストベースで作成したいと依頼がありました。
画像を作り変える手間が面倒なので、ソースに記述している数値を変更するだけでグラフが生成される仕組みが欲しいとの事でした。

いろいろググってみた結果「CanvasJS」と言うjQueryがとっても良い感じだったので、いろいろ実験をしてみました。
非常に簡単にいろいろな種類のグラフを生成出来る素晴らしいプラグインです。

個人使用は無料ですが、商用利用は有償となります。
詳しくはココを参照

CanvasJSの設定方法

まずはcanvasjsのjsファイルを読み込みます。
下のコードをhead内に貼り付けてください(グラフの直前でもOK)。

<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>

続いてグラフ描画の設定を行います。
設定は簡単で、死ぬほど大量に用意されている公式サイトのパラメーターをガンガン追加していって、「dataPoints」って言う所に項目名(label)と数値を入力するだけです。
パラメーターが多すぎて自分がやりたい事を探すのが困難ですが、わかりやすく画像付きで説明してくれているので、根気強く探しましょう。

普通の棒グラフ

いたって普通の棒グラフです。
これは何一つパラメーターを設定していない初期状態の物です。
棒グラフも太すぎてカラフルだし、横ラベルも普通に横書きでかっこ悪いね。
デフォルトでは幅(width)が100%で生成されてしまうので、幅の調整もしなければいけません。
カーソルを合わせた時に現れるバルーン(toolTip)もイマイチかっこ悪い感じ。
この無加工のグラフを生成するコードは以下の物です。
シンプルでしょ?

<script>
window.onload = function () {

var chart1 = new CanvasJS.Chart("chartContainer1", {
  data: [{
    type: 'column',
    dataPoints: [
      { label: "2012/5", y: 1425.94 },
      { label: "2013/5", y: 1745.08 },
      { label: "2014/5", y: 541.78 },
      { label: "2015/5", y: 699.59 },
      { label: "2016/5", y: 895.21 },
    ]
  }]
});
chart1.render();

}
</script>

4行目と16行目の「chart1」は同じに、4行目の「chartContainer1」はグラフを表示させる21行目のdivのid名にしてください。
6行目の「type:’column’」で棒グラフを指定し、7行目の「dataPoints」にlabelや数値を入力するだけで完成です。
では、これを格好良くカスタマイズしてみましょう。

パラメーターを設定した棒グラフ

どうでしょう?
だいぶスタイリッシュになったと思いませんか?
下のコードを見ると、ごちゃごちゃ書き足したように見えるかもしれませんが、自分好みになるようにパラメーターを追加していっただけなんです(黄色背景行)。
一部、subtitlesやtoolTipなど、書き方が特殊な項目がありますが、それも公式サイトのパラメーター一覧に書いてあるのでコピペで大丈夫です。
この棒グラフのソースはこんな感じ。

<script>
window.onload = function () {

//ここから
var chart2 = new CanvasJS.Chart("chartContainer2", {
  animationEnabled: true, 
  animationDuration: 2000,
  title: { text: '売上額', fontColor: '#222', fontSize: 16, margin: 15 },
  subtitles:[{ text: '単位:百万円', fontColor: '#555', fontSize: 12, margin: 15 }],
  width: 450,
  height: 350,
  dataPointMaxWidth: 30,
  axisX: { labelAngle: -45, labelFontSize: 14, labelFontColor: '#222' },
  axisY: { prefix: '¥', labelFontSize: 14, labelFontColor: '#222' },
  toolTip: {
    fontStyle: 'normal',
    content: "{label}
売上額:{y}(百万円)", backgroundColor: 'rgba(0,0,0,0.8)', fontColor: '#fff', borderColor: 'rgba(0,0,0,0.8)' }, data: [{ color: '#d47d7a', type: 'column', cursor: "pointer", dataPoints: [ { label: "2012/5", y: 1425.94 }, { label: "2013/5", y: 1745.08 }, { label: "2014/5", y: 541.78 }, { label: "2015/5", y: 699.59 }, { label: "2016/5", y: 895.21 }, ] }] }); chart2.render(); //ここまで } </script>

んで、ここで設定したパラメーターは以下のとおり。

animationEnabled グラフ描画をアニメーション化(読込時に伸びてく)
animationDuration 上記アニメーションの時間
title グラフ上部に記述されるタイトル
subtitles タイトル下のサブタイトル
width グラフの幅(指定しないと100%になる)
height グラフの高さ
dataPointMaxWidth 棒グラフの幅
axisX 横項目の設定(labelAngleで斜めにしてる)
axisY 縦項目の設定(prefixはラベル前に記述したいテキスト)
toolTip 棒グラフにカーソルを乗せた時に表示されるバルーン
{}の中にlabelとかyとか書けば読み込まれる
data グラフを生成する上で必要な値の設定
typeでグラフの種類
dataPointsで数値とか
color グラフの色を変える
cursor グラフにカーソルを乗せるとpointerになるようにする

上記のパラメーターを設定すれば、普通のグラフを作成する上では十分だと思います。

折線や積算などのグラフも簡単に作れます

折れ線グラフ

これを折れ線グラフにしたい場合は「type: ‘column’」を「type: ‘line’」にするだけでOKです。
それ以外の記述は棒グラフの物とまんま同じです。

積算棒グラフ

このグラフは複数の数値の合計を月毎にまとめた積算グラフです。
グラフのタイプを「type:”stackedColumn”」にし「data」内の記述を複数書きます。
棒グラフにカーソルを乗せると説明文が個別に出て、グラフ下部のジャンルをクリックすると、表示非表示を切り替える事も出来ます。

下部のジャンルクリックで表示を切り替えるためには「name」「legendText」「showInLegend」を追加し、最後に79行目〜90行目の記述を追加します。
その際、87行目の「chart4」の所を4行目と92行目と同じにする事も忘れずに。
たったこれだけでOKです。
そのコードは以下の通り。

<script>
window.onload = function () {

var chart4 = new CanvasJS.Chart("chartContainer4", {
  animationEnabled: true,
  animationDuration: 2000,
  title: { text: '売上額', fontColor: '#222', fontSize: 16, margin: 15 },
  subtitles:[{ text: '単位:百万円', fontColor: '#555', fontSize: 12, margin: 15 }],
  width: 450,
  height: 350,
  dataPointMaxWidth: 20,
  axisX: { labelAngle: -45, labelFontSize: 14, labelFontColor: '#222' },
  axisY: { prefix: '¥', labelFontSize: 14, labelFontColor: '#222' },
  toolTip: {
    fontStyle: 'normal',
    content: "{label}<br>{legendText}:{y}(百万円)",
    backgroundColor: 'rgba(0,0,0,0.8)',
    fontColor: '#fff',
    borderColor: 'rgba(0,0,0,0.8)'
  },
  data: [ {
    type: "stackedColumn",	
    color: '#B0D0B0',
    name: "北陸",
    legendText: "北陸",
    showInLegend: true, 
    cursor: "pointer",
    dataPoints:[
      { label: "2012/5", y: 61955 },
      { label: "2013/5", y: 74513 },
      { label: "2014/5", y: 86487 },
      { label: "2015/5", y: 93775 },
      { label: "2016/5", y: 103075 },
    ]
  }, {
    type: "stackedColumn",	
    color: '#ef9797',
    name: "信越",
    legendText: "信越",
    showInLegend: true,
    cursor: "pointer",
    dataPoints:[
      { label: "2012/5", y: 14136 },
      { label: "2013/5", y: 17417 },
      { label: "2014/5", y: 22319 },
      { label: "2015/5", y: 25081 },
      { label: "2016/5", y: 29378 },
    ]
  }, {
    type: "stackedColumn",	
    color: '#7fabdb',
    name: "北関東",
    legendText: "北関東",
    showInLegend: true,
    cursor: "pointer",
    dataPoints:[
      { label: "2012/5", y: 45 },
      { label: "2013/5", y: 1245 },
      { label: "2014/5", y: 5368 },
      { label: "2015/5", y: 8854 },
      { label: "2016/5", y: 15946 },
    ]
  }, {
    type: "stackedColumn",	
    color: '#d6cc60',
    name: "東海近畿",
    legendText: "東海近畿",
    showInLegend: true,
    cursor: "pointer",
    dataPoints:[
      { label: "2012/5", y: 0 },
      { label: "2013/5", y: 0 },
      { label: "2014/5", y: 2380 },
      { label: "2015/5", y: 10282 },
      { label: "2016/5", y: 20946 },
    ]
  } ],

  legend: {
    cursor: "pointer",
    itemclick: function(e) {
      if ( typeof ( e.dataSeries.visible ) === "undefined" || e.dataSeries.visible ) {
        e.dataSeries.visible = false;
      } else {
        e.dataSeries.visible = true;
      }
    chart4.render();
    }
  },
});

chart4.render();

}
</script>

比較棒グラフ

この棒グラフは2つの数値を比較した棒グラフです。
これも下部のジャンルをクリックで表示非表示を切り替える事が出来ます。
これはグラフのタイプを通常の棒グラフである「type:”column”」のまま、「data」内に2つ記述するだけです。

<script>
window.onload = function () {

var chart5 = new CanvasJS.Chart("chartContainer5", {
  animationEnabled: true,
  animationDuration: 2000,
  title: { text: '店舗A / 店舗B', fontColor: '#222', fontSize: 16, margin: 15 },
  subtitles:[{ text: '単位:百万円', fontColor: '#555', fontSize: 12, margin: 15 }],
  width: 450,
  height: 350,
  dataPointMaxWidth: 20,
  axisX: { labelAngle: -45, labelFontSize: 14, labelFontColor: '#222' },
  axisY: { prefix: '¥', labelFontSize: 14, labelFontColor: '#222' },
  toolTip: {
    fontStyle: 'normal',
    content: "{label}<br>売上額:{y}(百万円)",
    backgroundColor: 'rgba(0,0,0,0.8)',
    fontColor: '#fff',
    borderColor: 'rgba(0,0,0,0.8)'
  },
  data: [ {
    type: "column",	
    color: '#B0D0B0',
    name: "店舗A",
    legendText: "店舗A",
    showInLegend: true, 
    cursor: "pointer",
    dataPoints:[
      { label: "2012/5", y: 11082 },
      { label: "2013/5", y: 13673 },
      { label: "2014/5", y: 17315 },
      { label: "2015/5", y: 21983 },
      { label: "2016/5", y: 28188 },
    ]
  }, {
    type: "column",	
    color: '#ef9797',
    name: "店舗B",
    legendText: "店舗B",
    showInLegend: true,
    cursor: "pointer",
    dataPoints:[
      { label: "2012/5", y: 33824 },
      { label: "2013/5", y: 40928 },
      { label: "2014/5", y: 51772 },
      { label: "2015/5", y: 64550 },
      { label: "2016/5", y: 78417 },
    ]
  } ],

  legend: {
    cursor: "pointer",
    itemclick: function(e) {
      if ( typeof ( e.dataSeries.visible ) === "undefined" || e.dataSeries.visible ) {
        e.dataSeries.visible = false;
      } else {
        e.dataSeries.visible = true;
      }
    chart5.render();
    }
  },
});

chart5.render();

}
</script>

商用利用は有償です

と言った感じで、非常に簡単な設定でグラフを生成できるCanvasJSですが、商用利用する為にはライセンスを買わなければいけません。
internal applicationのSingle Developer Licenseで約35,000円と決して安くはないですが、こだわりを持ったクライアントさんの要望は応えられるスクリプトだと思いますよ。

設定が本当に簡単なのでお勧めですよ。