Chartjs-Chartjs: Make some ticks (Sunday, Saturday) red

0👍

According to Chart.js documentation, the option ticks.fontColor doesn’t accept an array but a simple string.

You can however define the style of your weekend ticks through the ticks.major configuration as follows.

ticks: {
  major: {
     enabled: true,
     fontStyle: 'bold',
     fontColor: 'red'
  }
},

Further you need to mark the desired ticks as major through the afterBuildTicks callback.

afterBuildTicks: (scale, ticks) => {
  ticks.forEach(t => {
    const day = new Date(t.value).getDay();
    t.major = (day == 0 || day == 6);
  });
  return ticks;
}

Please take a look at the runnable code snippet below.

const dates = [];
let day = new Date('2020-01-01');
for (let i = 0; i < 20; i++) {
    dates.push(new Date(day.getFullYear(), day.getMonth(), day.getDate()));
    day.setDate(day.getDate() + 1);
};

function generateData() {
  return dates.map(d => ({ x: d, y: Math.floor(Math.random() * 10) + 1 }));
};

new Chart('myChart', {
  type: 'bar',
  data: {
    datasets: [{
        label: 'My Dataset',
        data: generateData(),
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        borderWidth: 1
      }        
    ]
  },
  options: {
    scales: {
      xAxes: [{
        offset: true,
        type: 'time',
        time: {
          unit: 'day',
          displayFormats: {
            day: 'dd D MMM',
            month: 'dd D MMM'            
          },
          tooltipFormat: 'dd D MMM'
        },
        ticks: {  
          major: {      
            enabled: true,
            fontStyle: 'bold',
            fontColor: 'red'
          }
        },
        afterBuildTicks: (scale, ticks) => {
          ticks.forEach(t => {
            const day = new Date(t.value).getDay();
            t.major = (day == 0 || day == 6);
          });
          return ticks;
        }
      }],
      yAxes: [{
        ticks: {      
          beginAtZero: true,
          stepSize: 2
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.0/Chart.bundle.min.js"></script>
<canvas id="myChart" height="100"></canvas>

Leave a comment