Chartjs-How should data be structured for lineplots with vue/chart.js

0👍

Finally got it; I needed to re-read the doc for Chartjs. So here’s the mounted function now. See that I had to put in x and y values for each point.

async mounted () {
  this.loaded = false;
  try {
    let usercpu = [];
    await fetch("http://server/api/load/server02")
    .then(stream => stream.json())
    .then(mydata => { mydata.forEach(record => { 
      usercpu.push( { y: record.cpu.user, x: record.date });});});
    this.loaded = true;
    this.chartdata = { 
      datasets: [ {
        fill: false, 
        pointRadius: 0, 
        borderWidth: 2,
        label: 'CPU', 
        data: usercpu 
        } ] };
  } catch (e) {
    console.error(e)
  }
}

Also, in the data portion of the default function I had to add axes. I’m not exactly sure why, but even when the data was okay (above) I still couldn’t see the plot. So when I added the axes, there everything was:

options: {
    scales: {
        xAxes: [{
            type: 'time',
            time: {
                  unit: "hour",
                  displayFormats: {
                    hour: "M/DD @ hA"
                  },
                  tooltipFormat: "MMM. DD @ hA"
                },
                scaleLabel: {
                  display: true,
                  labelString: "Date/Time"
                },
            ticks: { autoSkip: true, maxTicksLimit: 5},
            position: 'bottom'
        }],
        yAxes: [{
            ticks: {
                suggestedMin: 0,
                suggestedMax: 10
            }
        }]
    } 

And of course I had to include the options in the directive:

    <template>
    <div id="app">
        <div class="container">
        <div id="cpu">
        <h2>Server02</h2>
        <line-chart v-if="loaded"  :chartdata="chartdata" :options="options"></line-chart>
        </div>
        </div>
    </div>
    </template>

Leave a comment