Home > Software design >  Plot Chart.js scatter graph in Django using huge data
Plot Chart.js scatter graph in Django using huge data

Time:09-05

I'm developing a scatter graph to visualize the trend of product volume for every product count.

x: product count
y: product volume

From django view, two array list was pass to chart javascript in django template. Here is the code:

<script>
  const volume = {{product_volume}} // <--- array list of product_volume
  const count = {{product_count}} // <--- array list of product_count
  
  const p1ctx = document.getElementById('VolumeChart');
  const P1Chart = new Chart(p1ctx, {     
        data: {
            datasets: [{
              type: 'scatter',
              label: 'Volume',
              data: volume, // <-------------------- Target to assign 'x' and 'y' data
              backgroundColor: 'rgb(255, 99, 132)'
            }],
        },
       .
       .
       .
</script>

However, with huge data (approx.: 15,000), how can I simplify the process of data labelling in the JavaScript using array list of product count and product volume?

CodePudding user response:

According to the documentation for Chart.js the scatter chart accepts data as an array with {x: ..., y: ...} pairs.

To reshape the two arrays volume and count into that shape, you'd do

const data = count.map((x, index) => ({x, y: volume[index]}));

assuming they're the same length.

  • Related