Adjust the font color of the X and Y axis

Is there a way to customize the color of the X and Y axes labels in Chart.js? I attempted to use the fontColor property within scaleLabel, but I suspect I may be placing it incorrectly?

I experimented with placing it under scale as suggested by the source code, which can be seen here. I also tried within scales and even inside xAxes.

var options = {
type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: 'red',
            borderWidth: 1
        }]
    },
    options: {
        scale: {
            scaleLabel:{
                fontColor: 'red'
            }
        },
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
 };

View example online

https://i.sstatic.net/U1mgk.jpg

I have consulted the documentation, but it doesn't provide clear guidance. Unfortunately, Chart.js lacks sufficient examples, making it challenging to navigate at times...

Answer №1

$(function(){
var ctx = document.getElementById("myChart");
//Customizing Chart Colors
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
       legend:{labels: {fontColor: 'orange'}},
      title: {
            display: true,
            fontColor: 'blue',
            text: 'Custom Chart Title'
        },
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true,
                    fontColor: 'red'
                },
            }],
          xAxes: [{
                ticks: {
                    fontColor: 'green'
                },
            }]
        }      
    }
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

You can use fontColor inside ticks/label/legend:labels for a particular axis,

options: {
        legend: {
             labels: {
                  fontColor: 'orange'
                 }
              },
        title: {
            display: true,
            fontColor: 'blue',
            text: 'Custom Chart Title'
        }     ,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true,
                    fontColor: 'red'
                },
            }],
          xAxes: [{
                ticks: {
                    fontColor: 'green'
                },
            }]
        } 
    }

or change the defaultFontColor to change font color of entire text elements drawn on the canvas.

 Chart.defaults.global.defaultFontColor='red';

Answer №2

Although I may be a bit late in responding to this query, the information provided here could prove beneficial to those seeking answers.

When working with Chart.js, you can customize the appearance of scale labels and ticks using the settings below.

options: {
    scales: {
        xAxes: [{
            display: true,
            scaleLabel: { // Customizing the scale label
                display: true,
                labelString: 'Name of X axis',
                fontColor: '#000000',
                fontSize: 10
            },
            ticks: {
                fontColor: "black", // Formatting the ticks displayed on the axis/labels
                fontSize: 14
            }
        }],
        yAxes: [{
            display: true,
            scaleLabel: {
                display: true,
                labelString: 'Name of Y axis',
                fontColor: '#000000',
                fontSize: 10
            },
            ticks: {
                fontColor: "black",
                fontSize: 14
            }
        }]
    }
}

For a comprehensive list of properties, please consult the Chart.js documentation. Make sure to thoroughly understand all the properties before proceeding with your implementation.

Wishing you success in your coding endeavors!

Answer №3

Exploring React JS with Create React App

"chart.js": "^3.7.0",
"react-chartjs-2": "^4.0.0",

I encountered a challenge while working on this issue, and although the suggested solution didn't quite solve it for me, I made some adjustments to get it working successfully.

Below is the modified code that ended up resolving the problem. Hopefully, this can assist someone else facing a similar issue...

https://i.sstatic.net/1pctB.png

const options = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
        legend: {
            position: 'top',
            labels: {
                color: "#ffffff",
            }
        },
        title: {
            display: true,
            text: 'License Usage',
            color: "#ffffff"
        },
    },
    scales: {
        yAxes: {
            ticks: {
                color: "#ffffff"
            },
        },
        xAxes: {
            ticks: {
                color: "#ffffff"
            },
        }
    },
};

Answer №4

By configuring the options as shown below, you can easily change the font color of axes label values. I personally tested this on jsfiddle and it successfully modified the font color. The same approach also worked for my chart within a rails application. ...

options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero:true,
                fontColor:'red'
            }
        }]
    }
}

...

Answer №5

If you want to customize the ticks and axes labels on your chart object, follow these steps:

const adjustLabelColors = (label) => {
    label.scaleLabel.fontColor = customColor;
    label.ticks.fontColor = customColor;
    label.ticks.minor.fontColor = customColor;
    label.ticks.major.fontColor = customColor;
};
chartConfig.options.scales.xAxes.forEach((label) => adjustLabelColors(label));
chartConfig.options.scales.yAxes.forEach((label) => adjustLabelColors(label));
chartConfig.update();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choose Status Menu DiscordJS version 14

Is there a way to get help with changing the bot's status if it's not working properly? The value of the variable "statuses" is set as status, but the status itself does not change. Using client.user.setStatus('dnd'); can sometimes work ...

Error with SwitchMap on ActivatedRoute.paramMap

When I try to run the ngOnInit method of my component, I encountered an error with the following line of code. this.products$ = this.route.paramMap.switchMap((params: ParamMap) => this.getProductsForType(params.get('type'))); The error mes ...

"Within the boundaries of two tags, eliminate any spaces when using the display property set

I'm a bit confused about the behavior of display:inline-block. I noticed that when I use inline-block, it displays content in a smaller space across two tags. However, when I switch to using float: left, everything works fine. Does anyone have an ide ...

angular.js:13920 Alert: [ngRepeat:dupes] Multiple occurrences in a repeater

I encountered an issue while attempting to parse a JSON file and map it in HTML. Here is the JavaScript code snippet: searhController.orderlogs.results = JSON.stringify(response.data); This is how it's implemented in Angular: <tr ng-hide="searh ...

Ways to safeguard my Node.js Blockchain

Recently, I delved into coding my own Blockchain in order to gain a deeper understanding of the concept. You can check out my code on GitHub here: https://github.com/Snixells/js-blockchain. I've successfully implemented the creation of Blockchain + ...

How to Retrieve the Index of a Value within an Array in VUE.js

I am facing an issue where I want to update the status of tasks based on a certain method call. However, the challenge lies in obtaining the index of the specific item within the array in order to modify its status. Here is my HTML setup: <div class="m ...

Guide on excluding certain words within a paragraph using PHP

In my database, there is a paragraph that looks like this: $str ="this is a paragraph i show shortly and when i click on the view more it will show completely for that i am using the ajax and retrieve it " I display it as follows: this is a paragrap ...

Errors encountered while starting Angular due to issues in package.json configuration

Summary: Encountered an error while using 'Angular' for the first time, indicating tsc was not found in the package.json file. Details: As a beginner with Angular, I followed an example from a book and attempted to start it with np ...

What is the best way to pass a module from the controller to a Jade/Pug template and then use it as an argument in an event handler within the template?

I passed the module 'naija' to a template from the controller in this way: res.render('testing', {title:"filter setting page", nigeria:naija }); The func ...

Encountered a problem during the insertion of data into the database through ajax and php

An issue is being encountered while trying to insert data into a database using Ajax, PHP, and jQuery. The code works smoothly on a localhost environment, but upon uploading it to the server, an error occurs. $('#sunsubmit').click(function(){ ...

Issue with JQuery dialog not triggering autocomplete

I have integrated the JQuery 1.7.2 and JQuery-UI 1.8.18 libraries with both http://docs.jquery.com/UI/Dialog and http://docs.jquery.com/UI/Autocomplete. On a standard page load, the autocomplete function works perfectly with a text box in a form. It' ...

Mouse click failing to trigger CSS property update

I am attempting to create an accordion feature. I want the accordion to expand when hovering over the "accordion head," and also show/hide the accordion body when clicking on the "accordion head." I have successfully implemented the show/hide functionalit ...

Exploring nested JSON data to access specific elements

When I use console.log(responseJSON), it prints the following JSON format logs on the screen. However, I am specifically interested in printing only the latlng values. When I attempt to access the latlng data with console.log(responseJSON.markers.latlng) o ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: https://i.sstatic.net/jNiaO.png My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code s ...

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...

The initial value in useEffect is not being updated by useState

I am currently implementing a like feature for my web application. The issue lies in the fact that my setLike function is not updating the state even after using setLike(!like). I verified this by adding console.log() statements before and after the setLik ...

Select: Exchange icon when clicked

UPDATE MENU ICON jsfiddle.net/a3MKG/83/ Can someone provide guidance on how to change the menu icon image upon clicking it? I would like the icon to switch to a different image (such as an X) once it has been clicked. Please Note: When the menu icon is c ...

Incapable of composing text using the MUI SearchBar

I'm having trouble with my Material UI search bar - it's not letting me type anything into it. How can I resolve this issue? Despite trying the suggested code snippets from other answers, I keep encountering errors when integrating them into my ...

"Enhance your Vue 3 experience with a stylish Instagram Feed featuring

Struggling to retrieve the most recent Instagram posts from a feed using Vue 3 and Axios due to Instagram's strict-origin-when-cross-origin policy causing constant blocks. All access tokens are properly configured. The Instagram Basic Display API gui ...

Using setInterval to eliminate duplicate markers from a leaflet map

I have been working on a Leaflet map project with markers. The markers' latlng data is fetched from JSON and displayed correctly. I tried using setInterval to refresh the method every 5 seconds to update the latlng positions, ensuring that old marker ...