Chartjs-Two charts using same options, but I need different titles for the charts

0👍

The important step is to do a deep copy of the options object.

Write down the options you want to use for both charts. You don’t need title: { ... } here because you will override it later.

let optionsDefault = {
  responsive: true,
  scales: { ... }
  // ...
}

Deep copy the options for both charts (JSON.parse & stringify is just one method for deep cloning, look here for more information about deep cloning).

let options1 = JSON.parse(JSON.stringify(optionsDefault))
options1.title = {
  display: true,
  text: "Chart 1"
}
let options2 = JSON.parse(JSON.stringify(optionsDefault))
options2.title = {
  display: true,
  text: "Chart 2"
}

Assign both options to the charts.

let chart1 = new Chart(ctx1, {
  type: "line",
  data: data,
  options: options1
});
let chart2 = new Chart(ctx2, {
  type: "line",
  data: data,
  options: options2
});

Leave a comment