Categories
JavaScript Answers

How to change label color with Chart.js and JavaScript?

Spread the love

Sometimes, we want to change label color with Chart.js and JavaScript.

In this article, we’ll look at how to change label color with Chart.js and JavaScript.

How to change label color with Chart.js and JavaScript?

To change label color with Chart.js and JavaScript, we set the fontColor.

For instance, we write

const ctx = document.getElementById("barChart");
const myChart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: ["label 1", "label 2"],
    datasets: [
      {
        label: "My Label",
        backgroundColor: "rgba(159,170,174,0.8)",
        borderWidth: 1,
        hoverBackgroundColor: "rgba(232,105,90,0.8)",
        hoverBorderColor: "orange",
        scaleStepWidth: 1,
        data: [4, 5],
      },
    ],
  },
  options: {
    legend: {
      labels: {
        fontColor: "blue",
        fontSize: 18,
      },
    },
    scales: {
      yAxes: [
        {
          ticks: {
            fontColor: "green",
            fontSize: 18,
            stepSize: 1,
            beginAtZero: true,
          },
        },
      ],
      xAxes: [
        {
          ticks: {
            fontColor: "purple",
            fontSize: 14,
            stepSize: 1,
            beginAtZero: true,
          },
        },
      ],
    },
  },
});

to set the fontColor of the labels by setting the fontColor in the options object property.

legend.labels has the options for the legend labels.

ticks has the styles for the ticks.

Conclusion

To change label color with Chart.js and JavaScript, we set the fontColor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *