2๐
$.getJSON("var/graph.json", function(data) {
var labels = data.test_data.map(function(e) {
return e[0];
});
var data = data.test_data.map(function(e) {
return e[1];
});
var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
backgroundColor: 'rgb(129, 198, 2228)',
borderColor: 'rgb(0, 150, 215)',
data: data
}]
},
options: {
responsive: 'true',
}
});
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="canvas" height="80"></canvas>
0๐
You need to transform the data
into a format suitable for a linear chart axis. For your line chart, you need to define labels
and the data
of the dataset. This can be done using the Array.map()
method.
data: {
labels: data.test_data.map(a => a[0]),
datasets: [{
data: data.test_data.map(a => a[1]),
...
}]
},
Please have a look at your amended code below.
const data = {
"test_data": [
["aa", "11"],
["bb", "123"],
["cc", "81"],
["dd", "12"],
["ee", "22"]
]
};
new Chart('canvas', {
type: 'line',
data: {
labels: data.test_data.map(a => a[0]),
datasets: [{
label: 'My Dataset',
data: data.test_data.map(a => a[1]),
fill: false,
borderColor: 'red'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="canvas" height="80"></canvas>
- [Chartjs]-Dashboard grid โ Chart.JS and CSS- issue widening two small horizontal bar graphs โ noob question
- [Chartjs]-Chartjs in Reactjs โ how can I update data dynamically?
Source:stackexchange.com