Chart Js, Style some ticks on the axis differently

Viewed 2455

I have a bar chart where on the x axis we have dates. I want to make the weekend days bold or give it a different colors.

window.myBar = new Chart(ctx, {
            type: 'bar',
            data: barChartData,
            options: {
                title: {
                    display: false,
                },
                tooltips: {
                    mode: 'index',
                    intersect: false
                },
                legend: {
                    display: true,
                    position: "top"
                },
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    xAxes: [{
                        stacked: true,
                        ticks: {
                            fontColor:'#CCCCCC',
                            callback: function(value, index, values) {
                                if (value.substring(0, 3) == 'Sat' || value.substring(0, 3) == 'Sun') {
                                    return value.toUpperCase();
                                } else {
                                    return  value;
                                }
                            },
                        }
                    }],
                    yAxes: [{
                        stacked: true,
                    }]
                }
            }
        });

I also looked into the minor ticks and major ticks configuration, but not sure if that's what i have to look into and how to implement that.

enter image description here

3 Answers

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

ticks: {
  major: {
     enabled: true,
     fontStyle: 'bold',
     fontColor: 'rgb(54, 143, 3)'
  }
},

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 have 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: 'Dataset 1',
        data: generateData(),
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        borderWidth: 1
      },
      {
        label: 'Dataset 2',
        data: generateData(),
        backgroundColor: 'rgba(255, 159, 64, 0.2)',
        borderColor: 'rgb(255, 159, 64)',
        borderWidth: 1
      },
      {
        label: 'Dataset 3',
        data: generateData(),
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgb(54, 162, 235)',
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      xAxes: [{
        offset: true,
        stacked: true,
        type: 'time',
        time: {
          unit: 'day',
          displayFormats: {
            day: 'ddd D MMM YYYY',
            month: 'ddd D MMM YYYY'            
          },
          tooltipFormat: 'ddd D MMM YYYY'
        },
        ticks: {  
          major: {      
            enabled: true,
            fontStyle: 'bold',
            fontColor: 'rgb(54, 143, 3)'
          }
        },
        afterBuildTicks: (scale, ticks) => {
          ticks.forEach(t => {
            const day = new Date(t.value).getDay();
            t.major = (day == 0 || day == 6);
          });
          return ticks;
        }
      }],
      yAxes: [{
        stacked: true,
        ticks: {      
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.0/Chart.bundle.min.js"></script>
<canvas id="myChart" height="100"></canvas>

Use ticks in xAxes.

xAxes: [{
            ticks: {
            fontStyle: "bold"
            }
            }]

I had a similar requirement and settled for changing the color of the gridline itself. The docs for styling indicate this is possible with the key color, nested under the scale configuration in the gridLines key.

The color of the grid lines. If specified as an array, the first color applies to the first grid line, the second to the second grid line and so on.

If you already know the order of your x-axis labels you can build an array that specifically colors some ticks. (like in OP, the weekend).

var barChartDataXaxis = ['Sun','Mon','Tues','Wed','Thurs','Fri','Sat'];
var xaxisDayMark = [];

for (let i = 0; i < barChartDataXaxis.length; ++i) {

        // standard grey line
        xaxisDayMark.push('rgba(0, 0, 0, 0.1)');

    if (barChartDataXaxis[i] == 'Sat' || barChartDataXaxis[i] === 'Sun') {

        // else some nice coloring
        xaxisDayMark.splice(i, 1, 'rgb(0, 0, 225)');

    }

}

window.myBar = new Chart(ctx, {
        type: 'bar',
        data: barChartData,
        options: {
            scales: {
                xAxes: [{
                    gridLines: {
                        color: xaxisDayMark // use our array here
                    }
                }]
            }
        }
    });
Related