How to read and plot json with chart.js?

by raven_corwin , in category: Javascript , 10 months ago

How to read and plot json with chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 10 months ago

@raven_corwin 

To read and plot a JSON data using Chart.js, you can follow these steps:

  1. First, include the Chart.js library in your HTML file. You can use a CDN link or include it locally.
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Create a canvas element in your HTML file where you want to display the chart.
1
<canvas id="myChart"></canvas>


  1. Read the JSON data using AJAX or fetch API. In this example, we'll use the fetch API to get the JSON data.
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. Process the JSON data and create a chart using the Chart.js library.
 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
    }
  });
}


  1. Customize the chart options as per your requirements. The example provided above creates a bar chart, but you can change the type and other properties to create different types of charts.


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.