[英]Django and Chart.js: Line-Chart with multiple Datasets
我正在嘗試使用 chart.js 和多個數據集創建折線圖(數據集的數量在其生命周期內可能會發生變化):
...來自我的“views.py”:
label = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
coworker = ['John Doe', 'Jane Doe', 'Michael Smith']
data = [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [3, 4, 2, 1, 5]]
如果這是一個只有一個數據列表和一個同事的折線圖,我的圖表通常如下所示:
<script>
$(document).ready(function(){
var ctx = document.getElementById('myChart1').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: {{ label|safe }},
datasets: [{
label: 'Some text...',
data: {{ data|safe }},
backgroundColor: ...,
borderColor: ...,
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}],
}
}
});
});
我已經嘗試像這樣遍歷我的數據...
<script>
$(document).ready(function(){
var ctx = document.getElementById('myChart1').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: {{ label|safe }},
datasets: [{
label: [{% for i in label%}"{{ i }}",{% endfor %}],
data: [{% for j in data %}{{ j }}, {% endfor %}],,
backgroundColor: ...,
borderColor: ...,
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}],
}
}
});
});
現在圖表和從“星期一”到“星期五”的標簽是可見的,但僅此而已......有誰知道,我做錯了什么,甚至有更好的解決方案?
謝謝,美好的一天!
您需要從可用數據中定義 3 個不同的數據集。
這在下面的可運行代碼片段中進行了說明。 不幸的是,我對 python 了解不多。 因此,這是一個純粹的 JavaScript 解決方案。 但是,我認為您可以輕松地包含 python 代碼以獲得相同的結果。
const label = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; const coworker = ['John Doe', 'Jane Doe', 'Michael Smith']; const data = [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [3, 4, 2, 1, 5]]; var myChart = new Chart('chart', { type: 'bar', data: { labels: label, datasets: [{ label: coworker[0], data: data[0], backgroundColor: 'red' }, { label: coworker[1], data: data[2], backgroundColor: 'blue' }, { label: coworker[2], data: data[2], backgroundColor: 'green' }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true, } }], } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="chart" height="90"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.