Chart.js: Add possibility to change style for each of the ticks

Created on 3 May 2016  ·  38Comments  ·  Source: chartjs/Chart.js

It would be great if in future there is a possibility to change style (color, bgcolor, font-weight) for each of the ticks. For example if one needs to show in XAxes that 7 May 2016 and 8 May 2016 are holidays on the linear graph - changes the style for this ticks on the XAxes. Now style is set once for all ticks.

help wanted enhancement

Most helpful comment

Can someone merge this into main pls?

All 38 comments

@moviesound this is a good idea. For anyone who comes across this, I'd be happy to merge a PR adding this.

This is an example. There may be placed array in fontColor (only for XAxes). The amount of color elements must be equal to the amount of the elements in data.labels.

<canvas id="graph-canvas" width="800" height="400"></canvas>

<script>
data = {
    labels: ["26 Apr","27 Apr","28 Apr","29 Apr","30 Apr","01 May","02 May","03 May"],
    datasets: [{
        label: "total",
        data: [2, 3, 4, 2, 3, 5, 6, 3]
        }]
};

var ctx = document.getElementById("graph-canvas");
var myLineChart = new Chart(ctx, {
    type: 'line',
    data,
    options: {
        scales: {
            xAxes: [{
                ticks: {
                    fontColor:['rgba(44,44,44,0.8)','rgba(44,44,44,0.8)','rgba(44,44,44,0.8)','rgba(178,31,31,1)','rgba(44,44,44,0.8)','rgba(44,44,44,0.8)','rgba(44,44,44,0.8)','rgba(44,44,44,0.8)'],
                    callback: function(tickValue, index, ticks) {
                        return tickValue;
                    }
                }
            }]
        }
    }
});
</script>

Then in chart.js near the row 6349 after the
helpers.each(this.ticks, function(label, index) {
there can be placed

if(Object.prototype.toString.call( tickFontColor ) === '[object Array]'){
    this.ctx.fillStyle = tickFontColor[index];
}

for chart.js 2.6.0 you should do the change @moviesound suggested, but in:
chart.js/src/core/core.scale.js at line 830, change:

context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;

to

if (Object.prototype.toString.call( tickFontColor ) === '[object Array]') {
    context.fillStyle = itemToDraw.major ? majorTickFontColor[index] : tickFontColor[index];
} else {
    context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;
}

and in line 798 change:

helpers.each(itemsToDraw, function(itemToDraw) {

to:

helpers.each(itemsToDraw, function(itemToDraw, index) {

@etimberg, could you provide an example on how to use 683e86e?

edit:
After noticing this commit I cloned @bevingtongroup's repo, built it, and used the new Chart.min.js file, I was able to achieve the following result:

image

Using the following in my Chart options:

 yAxes: [{
    ticks: {
        fontColor: ['white', '#89817b', 'white', '#89817b', 'white', '#89817b', 'white', '#89817b', 'white', '#89817b', 'white', '#89817b'],
        fontFamily: 'Gotham Book',
        fontFunction: function (tickIndex) {
            if (tickIndex % 2 !== 0) {
                return '14px "Gotham Book"';
            } else {
                return '30px "Gotham Book"';
            }
        },
        callback: function (value) {
            return '$' + abbreviate_number(value);
        }
    }
}],

@kneeki how did you build the repo? What are the commands?

@iursevla , I use Linux, here is the process:

cd ~/
git clone https://github.com/bevingtongroup/Chart.js.git
cd Chart.js
# Use apt to install npmjs if you haven't already
npm install
sudo npm install -g gulp
gulp build

Once it's built, you can use the code in my previous post to achieve the same effect.

Can someone merge this into main pls?

Is this now a default feature?
and if so, have the docs been updated?

@crabdul it seems this is not a default feature, so for now i recommend to copy https://github.com/bevingtongroup/Chart.js or copy the code base of this main repo and modify code yourself

oke.. i've tested the code of bevingtongroup, and it works like a charm... this really! should be pulled into this general repo

Any chance of merging this? it's been more than a year.

Are there any open PRs for this at the moment to make this change? If not, either somebody with the most knowledge of the issue can perhaps put one up, or I can try?

@rpearce you can try if you can. It's open source.

@iursevla I didn't want to spend the time if it was already done. I'll do my best!

+1, this feature would be really nice to have.

~@GrossoMoreira I'm going to see if I can do it over the next week; the more the merrier if you want to take a stab at it~ I'm super unfamiliar with this project and not sure I want to go down this path yet.

You could accomplish this with scriptable options. @etimberg has been working on adding them for each different chart type. E.g. here's a recent PR adding it for the line chart: https://github.com/chartjs/Chart.js/pull/5973

Possibly only bubble chart support scriptable options in the current release, but the code in master supports many more chart types, so 2.8.0 should allow you to accomplish this. I'm going to close this as implemented

Scriptable options for tick labels are not yet supported even in the master.

You could accomplish this with scriptable options...

I believe this is just for bubble, not for line (_Note: scriptable options are only supported by a few bubble chart options._). Anyway, I tried to use scriptable to change the color of each element of XAxes, but it always get the last color of the array and apply that for all items. @benmccann , do you have an example? I am really blocked by that.

@crabdul it seems this is not a default feature, so for now i recommend to copy https://github.com/bevingtongroup/Chart.js or copy the code base of this main repo and modify code yourself

Guys, a little help? Maybe is not the place to ask that, however will be helpfull to have here the complete way to use this _work around_ (and very cleaver) solution:
I have success with the solution @ortichon , and it is good enough to me to make my own custom copy of chartjs until it will be commit at Master. The problem is: how to make this copy to work? I created a new folder with this custom code (copy from chart.js - master), I runned the npm i, gulp build... But I am having problem to add that to my project... before it was inside my package.json, inside dependencies: "chart.js": "^2.7.2", now I need to use my customized folder inside my project, but how? inside the same package json, but pointing to my custom version, inside _dependencies_ as well? Very newbie this question, but has a long time i dont touch in import files / dependencies... someone can help me with that?

@Winnetou
I've just forked chart.js repo to my own account,
commited and pushed the changes I wanted,
and then added to my package.json:
"chart.js": "<your-account-name>/Chart.js"
then npm install and you're done.
so actually I'm installing the package directly from my Github repo

scriptable options are only supported by a few bubble chart options.

Yes, for 2.7.3. The latest code in master supports many more scriptable options.

is this feature available in master or do I have to use @benpdavison version of chart.js?

Does chartjs 2.8.0 support the different color axis for different ticks?

@etimberg Can you please merge these changes to master.

Wow 3 years no one does that.

The best way to implement this would be to use scriptable options, which are supported thoughout the library.

Right now, there's one set of options for major ticks and one set for minor ticks:
https://github.com/chartjs/Chart.js/blob/16bb94ebc1109500ce890175bc80415eb36c22d4/src/core/core.scale.js#L147

Instead, we could accept a function which takes a context parameter and provides the user with the chart, scale, tick, tickIndex, etc. Then _computeLabelItems could resolve a new set of font options by calling the function for each label.

The best way to implement this would be to use scriptable options, which are supported thoughout the library.

Right now, there's one set of options for major ticks and one set for minor ticks:
https://github.com/chartjs/Chart.js/blob/16bb94ebc1109500ce890175bc80415eb36c22d4/src/core/core.scale.js#L147

Instead, we could accept a function which takes a context parameter and provides the user with the chart, scale, tick, tickIndex, etc. Then _computeLabelItems could resolve a new set of font options by calling the function for each label.

I am using Vue-chartjs but strange that except for callbacks: {} other params such as fontColor or fontSize doesn't accept a function. And I am not sure which instance produces _computeLabelItems, oops.

@QiQiBiBi the scriptable tick options are only in the dev version. It's not yet released. If you build chart.js yourself you can get access to it

Is there any documentation on these scriptable options and this parseTickFontOptions? I am having trouble understanding how it works

Yes, there are some docs for 3.0.0-alpha here: https://www.chartjs.org/docs/next/axes/styling/

I'm a bit confused. I'm trying to get font colors to work in 3.0 and I can't get them to show at all. Even using the exact code from the migration guide, nothing seems to be happening: https://jsfiddle.net/egy8qcxu/

I'm unclear on how that page relates to the issue. Like I said, the code in the JS fiddle is ripped straight from the migration guide, yet it doesn't change the font: https://jsfiddle.net/egy8qcxu/ but even if I try to replicate the syntax on the page provided, that doesn't seem to work either: https://jsfiddle.net/egy8qcxu/2/

Am I missing something fundamental? Do I need to include anything beyond the chart.min.js for 3.0 for fonts to work?

The code in the migration guide has changed a bit in master and reflects the upcoming 3.0.0-alpha.2 release: https://www.chartjs.org/docs/master/getting-started/v3-migration/

Here's a sample from master that shows some ticks as being bolded: https://www.chartjs.org/samples/master/scales/financial.html

Figured out the problem: It seems I was using the wrong version. Originally I just googled Chart js 3.0 and downloaded the min from github. Replaced that min with the min included in the example pages and everything seems to be working now.

To anyone else having trouble, make sure you have the right version!

Seems that the 3.0.0-alpha.2 breaks the chartjs-plugin-datalabels plugin

Probably none of the plugins are compatible with 3.0 and will need to be updated when 3.0 final is released

Was this page helpful?
0 / 5 - 0 ratings