@raven_corwin
To read and plot a JSON data using Chart.js, you can follow these steps:
1
|
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> |
1
|
<canvas id="myChart"></canvas> |
1 2 3 4 5 6 7 8 9 |
fetch('data.json')
.then(response => response.json())
.then(data => {
// Process the JSON data and create a chart
createChart(data);
})
.catch(error => {
console.error('Error:', error);
});
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function createChart(data) {
// Extract the required data from the JSON object
const labels = data.map(item => item.label);
const values = data.map(item => item.value);
// Create a new Chart.js instance
const ctx = document.getElementById('myChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Data',
data: values,
backgroundColor: 'rgba(75, 192, 192, 0.8)', // Bar color
borderColor: 'rgba(75, 192, 192, 1)', // Border color
borderWidth: 1 // Border width
}]
},
options: {
responsive: true,
maintainAspectRatio: false
}
});
}
|
Note: Replace 'data.json' with the actual path to your JSON file.
This code will fetch the JSON data, process it, and create a bar chart using Chart.js library. You can modify the code according to your JSON data structure and chart type.