前提
Chart.js 2.9で積み上げ横棒グラフを作成しています。
datesets内の項目をJSONで受け取り、指定できるようにしたいです。
実現したいこと
例えば以下のJSONを受け取ると
[{"label": "STOP","data": 0.5,"backgroundColor": "rgba(220, 20, 60, 0.9)","borderColor": "rgba(0, 0, 0, 1)","borderWidth": 0.5},
{"label": "Alarm","data": 10,"backgroundColor": "rgba(255, 215, 0, 0.9)","borderColor": "rgba(0, 0, 0, 1)","borderWidth": 0.5}]
この時、上記の場合は、項目は2つだけですが
JSONに記述してある数だけ動的に増やして表示させたいです。
例えば、項目が3つに変化↓
[{"label": "STOP","data": 0.5,"backgroundColor": "rgba(220, 20, 60, 0.9)","borderColor": "rgba(0, 0, 0, 1)","borderWidth": 0.5},
{"label": "Alarm","data": 10,"backgroundColor": "rgba(255, 215, 0, 0.9)","borderColor": "rgba(0, 0, 0, 1)","borderWidth": 0.5},
{"label": "STOP","data": 1.5,"backgroundColor": "rgba(220, 20, 60, 0.9)","borderColor": "rgba(0, 0, 0, 1)","borderWidth": 0.5}]
該当のソースコード
項目数が固定の場合は、下記のように直接書きますが
JSONで受け取り、かつ、項目も増える可能性がある場合
どのように変数を用意して書けばいいのかわかりません。
取っ掛かりだけでも結構ですので、ご教示いただけませんでしょうか。。
JavaScript
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <meta charset="UTF-8"> 5 <title>棒グラフ</title> 6 <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"/> 7</head> 8 9<body> 10 11<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> 12 13<canvas id="myChart" width="800" height="100"></canvas> 14<script> 15var ctx = document.getElementById('myChart').getContext('2d'); 16 17var myChart = new Chart(ctx, { 18 type: 'horizontalBar', 19 data: { 20 labels: ["機器01"], 21 datasets: [{ 22 label: 'STOP', 23 data: [0.5], 24 backgroundColor: [ 25 'rgba(220, 20, 60, 0.9)' 26 ], 27 borderColor: [ 28 'rgba(0, 0, 0, 1)' 29 ], 30 borderWidth: 0.5 31 }, 32 { 33 label: 'Alarm', 34 data: [10], 35 backgroundColor: [ 36 'rgba(255, 215, 0, 0.9)' 37 ], 38 borderColor: [ 39 'rgba(0, 0, 0, 1)' 40 ], 41 borderWidth: 0.5 42 } 43 ] 44 }, 45 options: { 46 responsive: false, 47 scales: { 48 xAxes: [{ 49 stacked: true, 50 ticks: { 51 max: 12, 52 stepSize: 1, 53 } 54 }], 55 yAxes: [{ 56 stacked: true 57 }] 58 } 59 } 60}); 61</script> 62</body> 63</html>
試したこと
ここに問題に対して試したことを記載してください。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/11/23 01:00