[Chartjs]-Plot points on a line in chart.js

1👍

Assuming data.assay_values contains an array of numbers (for example [65, 59, 80, 81, 56, 55, 40]), and that you only want the chart to show the even values, you can use the below code to process your data array into a new array, only keeping the even numbers.

Keep in mind that you also have to build a new labels array because your dataset data array must be the same length as your chart labels (because each index in the data maps to the corresponding labels index).

Please note, since you didn’t provide any detail about your labels array in your question, this code assumes you have an array called labels that contains an array of strings. You will need to change this according how you defined your labels in your implementation.

var evenData = [];
var newLabels = [];

data.assay_values.forEach(function(e, i) {
  // only take the even values
  if (e % 2 === 0) {
    evenData.push(e);
    newLabels.push(labels[i]);
  }
});

Then change your chart.js chart config to use your new labels and data arrays like this.

var data = {
  labels: newLabels,
  datasets: [{
    label: 'Assay Values',
    fill: false,
    lineTension: 0,
    backgroundColor: "rgba(75,192,192,0.4)",
    borderColor: "rgba(75,192,192,1)",
    borderCapStyle: 'butt',
    borderDash: [],
    borderDashOffset: 0.0,
    borderWidth: 1,
    borderJoinStyle: 'miter',
    pointBorderColor: "rgba(75,192,192,1)",
    pointBackgroundColor: "#fff",
    pointBorderWidth: 1,
    pointHoverRadius: 5,
    pointHoverBackgroundColor: "rgba(75,192,192,1)",
    pointHoverBorderColor: "rgba(220,220,220,1)",
    pointHoverBorderWidth: 2,
    pointRadius: 1,
    pointHitRadius: 10,
    data: evenData,
    spanGaps: false
  }]
};

// configure your chart options here
var options = {};

// ctx is a jQuery instance or 2d context of the canvas of where we want to draw the chart.
var myLineChart = new Chart(ctx, {
  type: 'line', 
  data: data, 
  options: options 
});

Leave a comment