Chart JS V2.0 Line Chart Point Style II
サンプルの内容
以前のサンプルでは凡例の周りが、チャート内でポイントを結ぶ線になっている。 そのため、個人的に不満が残る結果だったのを修正する方法を説明する。
options.legend.labels.generateLabels を利用する方法の説明となる。
これが、
こうなります。微妙ですが大きな違いです。
最終結果
mulit line chart からの主な修正点
変更点は
options.legend.labels.generateLabels
を追加する。つまり、以下のようになる。
options: { legend: { labels: { generateLabels: function(chart){ return chart.data.datasets.map( function( dataset, i ){ return { text: dataset.label, fillStyle: dataset.backgroundColor, hidden: !chart.isDatasetVisible(i), lineCap: dataset.borderCapStyle, lineDash: [], lineDashOffset: 0, lineJoin: dataset.borderJoinStyle, lineWidth: dataset.pointBorderWidth, strokeStyle: dataset.borderColor, pointStyle: dataset.pointStyle, datasetIndex: i // extra data used for toggling the datasets }; }) } } }, }
ドキュメントの該当箇所
公式ドキュメントの
Legend label Configuration や、 Legend Item Interface を参考にする。 ただし、公式ドキュメントに記載されてないこともある。 そこはソースコードで補完する必要があった。
generateLabels
generateLabels メソッドを使って凡例を生成しているが、 凡例の図の設定に、点を結ぶ線の設定で描画している。 これが諸悪の根源である。
該当箇所は以下の通り。
generateLabels: function(chart) { var data = chart.data; return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) { return { text: dataset.label, fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]), hidden: !chart.isDatasetVisible(i), lineCap: dataset.borderCapStyle, lineDash: dataset.borderDash, lineDashOffset: dataset.borderDashOffset, lineJoin: dataset.borderJoinStyle, // This parameter, "borderWidth" is not good. lineWidth: dataset.borderWidth, strokeStyle: dataset.borderColor, pointStyle: dataset.pointStyle, // Below is extra data used for toggling the datasets datasetIndex: i }; }, this) : []; }
これを利用して lineWidth を datasets[*].pointBorderWidth に変更する。
- fillStyle は今回 Array では設定してないから三項演算子を省略
- lineDash, LineDashOffset は不要なので無効化
- lineWidth は dataset.pointBorderWidth に置き換える
options: { legend: { labels: { generateLabels: function(chart){ return chart.data.datasets.map( function( dataset, i ){ return { text: dataset.label, fillStyle: dataset.backgroundColor, hidden: !chart.isDatasetVisible(i), lineCap: dataset.borderCapStyle, lineDash: [], lineDashOffset: 0, lineJoin: dataset.borderJoinStyle, //This parameter is changed from borderWidth to pointBorderWidth. lineWidth: dataset.pointBorderWidth, strokeStyle: dataset.borderColor, pointStyle: dataset.pointStyle, datasetIndex: i // extra data used for toggling the datasets }; }) } } }, }
戻り値
公式ドキュメントにある説明では、以下のように 10 アイテムのようになっているが、 元々のメソッドの最後にある datasetIndex は抜けている。 これが無いと凡例をクリックして、表示・非表示を切り替える機能が使用不可能となる。
{ text: String, fillStyle: Color, hidden: Boolean, lineCap: String, lineDash: Array[Number], lineDashOffset: Number, lineJoin: String, lineWidth: Number, strokeStyle: Color pointStyle: String }