チャートライブラリの使い方(5)「動的に系列データを追加する」
hifiveのチャートライブラリの紹介です。今回は動的に系列データを追加する方法を紹介します。
現在、動的な系列データの追加は積み上げグラフの場合のみサポートされています。実際の動作は下の画像のようになります。
サンプルはこちらのURL にて確認できます。ベースはチャートライブラリの使い方(1)「基本編」 | hifive開発者ブログのグラフです。
ボタンを追加
まずHTMLにボタンを追加します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p> | |
<button id="add"> | |
データ系列追加 | |
</button> | |
</p> |
追加イベントを作成
追加時の処理ですが、これはシリーズデータを作成(配列)し、チャートコントローラの addSeries を実行します。配列であることに注意してください。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
this._chartController.addSeries([this._createNewSeries()]); |
色の生成処理を追加
これはおまけですが、グラフの系列データの色をランダムで生成するようにしました。ランダムなカラーコードを生成 – Qiitaを参考にさせてもらいました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_createNewSeries: function() { | |
var data = createChartDummyData(400, 100); // ダミーデータを生成 | |
// 系列定義 | |
var color = GenerateColor(); | |
return { | |
name: 'series_'+color, | |
type: 'stacked_line', | |
data: data, | |
propNames: { | |
y: 'val' | |
}, | |
fillColor: "#" + GenerateColor(), | |
color: "#" + color | |
}; | |
} | |
function GenerateColor() { | |
return Math.floor(Math.random()*16777215).toString(16); | |
} |
色コードを系列データの名前に適用しています。また、fillColor(塗りつぶしの色)に対しても別なランダムな色を適用しています。塗りつぶしについてはチャートライブラリの使い方(2)「データを塗りつぶす」 | hifive開発者ブログを参考にしてください。
これで完了です。後はボタンを押すだけで系列データが生成されてグラフが自動的に描画更新されます。
データを非同期で読み込んで描画する際にも利用できるでしょう。サンプルを参考の上、実装してみてください。
コメントは受け付けていません。