Chartjs-How to add color to each data in chartjs scatter plot

0👍

under your let dataSet put another array let backgroundColor and instead of setting pointBackgroundColor in your objects in the if, push that collor into the array, after that add this array to the dataset as backgroundColors so you will get something like this:

  let dataSet = [];
  let backgroundColor: [];  

  Object.keys(stateData).map((item) => {
    let short = {};
    let medium = {};
    let long = {};
    if (stateData[item].horizon === "Short-term") {
      short["label"] = "Short-term";
      backgroundColor.push("rgba(201, 120, 12, 1)")
      short["x"] = stateData[item].impact;
      short["y"] = stateData[item].occurrence;
      dataSet.push(short);
    }
    if (stateData[item].horizon === "Medium-term") {
      medium["label"] = "Medium-Term";
      backgroundColor.push("rgba(201, 120, 12, 1)")
      medium["x"] = stateData[item].impact;
      medium["y"] = stateData[item].occurrence;
      dataSet.push(medium);
    }
    if (stateData[item].horizon === "Long-term") {
      long["label"] = "Long-Term";
       .push("rgba(201, 120, 12, 1)")
      long["x"] = stateData[item].impact;
      long["y"] = stateData[item].occurrence;
      dataSet.push(long);
    }
  });


  const data = {
    datasets: [
      {
        data: dataSet,
        backgroundColor
      }
    ]
  };
  const options = {
    title: {
      display: true,
      text: "Risks"
    },
    scales: {
      xAxes: [
        {
          ticks: {
            max: 10,
            min: 0,
            stepSize: 0.5
          }
        }
      ],
      yAxes: [
        {
          ticks: {
            max: 10,
            min: 0,
            stepSize: 0.5
          }
        }
      ]
    }
  };

  return (
    <div className="w-full h-9/12">
      <div className="chartjs-wrapper">
        <Scatter data={data} options={options} />
      </div>
    </div>
  );
}

Leave a comment