Is there a way to modify the language for the 'months' displayed on the date axis in Chart JS?

I need to translate the month string on the date axis (x-axis) in my Chart JS data plot from '20 Dec 2018' to a different language. I thought it would automatically adjust based on the browser's language settings, but that doesn't seem to be the case.

Additionally, I am also looking for a way to translate the tooltip when hovering over a data point in the chart.

Answer №1

I successfully resolved this issue by implementing callback functions on the xAxis : ticks and tooltips : title when setting up the chart.

Below is the code snippet that initializes the chart.js:

<script>

var data = JSON.parse('<?php echo $data?>');

var ctx = document.getElementById("points-given-chart").getContext('2d');

var chartPoints = new Chart( ctx, { 

    type: 'line',
    data: {
        datasets: [
            {
                data: data,
                borderWidth: 3,
                label: 'Pontos',
                borderColor: 'rgba(246, 185, 59,1.0)',
                backgroundColor: 'rgba(250, 211, 144,1.0)',
            }
        ]
    },
    options: {
        responsive: true,
        title:      {
            display: false,
            text:    "Pontos"
        },
        scales:     {
            xAxes: [{
                type: "time",
                time: {
                    unit: 'day',
                    tooltipFormat: 'D MMM, YYYY',
                    displayFormats: {
                        day: 'D MMM'
                    },
                    distribution: 'series'
                },
                scaleLabel: {
                    display:     true,
                },
                ticks : {

                    // Callback function for translating labels:
                    callback: function( label, index, labels ) {

                        return translate_this_label( label );
                    }
                }
            }],
            yAxes: [{
                scaleLabel: {
                    display:     false,
                    labelString: 'Pontos'
                },
                ticks : {
                    beginAtZero : true,
                    callback: function( label, index, labels ) {
                        if ( label > 1 )
                            return formatNumber( label, 0, ',', '.');
                        else
                            return label;
                    }
                }
            }]
        },
        elements: {
            line: {
                tension: 0.2, // disables bezier curves
            }
        },
        legend: {
            display: false
        },

        tooltips: {
            callbacks: {

                // Callback function for translating tooltips:
                title: function( data ) {

                    return translate_this_label( data[0].xLabel );
                },
                label: function ( item, data ) {

                        return 'Pontos: ' + formatNumber( item.yLabel, 0, ',', '.');
                }
            }
        }
    }
});
</script>

Furthermore, I have included helper functions to handle the translation process:

function translate_month( month ) {

    var result = month;

    switch(month) {

        case 'Feb':
            result = 'Fev' ;
            break;
        case 'Apr':
            result = 'Abr' ;
            break;
        case 'May':
            result = 'Mai' ;
            break;
        case 'Aug':
            result = 'Ago' ;
            break;
        case 'Sep':
            result = 'Set' ;
            break;
        case 'Dec':
            result = 'Dez' ;
            break;

    }

    return result;
}


function translate_this_label( label ) {

    month = label.match(/Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Nov|Dec/g);

    if ( ! month ) 
        return label;

    translation = translate_month( month[0] );
    return label.replace( month, translation, 'g' );
}

Answer №3

If you are using Chart.js version 2.8 or higher along with moment.js version 2 or above, there is a convenient way to translate axis labels automatically by utilizing chartjs-adapter-moment:

import moment from "moment";
import "moment/locale/nl";
import Chart from "chart.js";
import "chartjs-adapter-moment";

moment.locale("nl");

new Chart(...);

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

Having trouble navigating with router.navigate and utilizing local storage?

I have a code that utilizes router.navigate to direct the user to a specific location abrirLista(categoria, id) { localStorage.setItem('categName', JSON.stringify(categoria)); const slug = slugify(categoria); this.router.navigate(['/lista&ap ...

Is it necessary to clean up the string to ensure it is safe for URLs and filenames?

I am looking for a way to generate a URL-safe filename in JavaScript that matches the one created using PHP. Here is the code snippet I currently have in PHP: <?php $clean_name = strtr($string, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕ ...

Combining click and change events in JQuery

Is it possible to listen for both click and change events in one code block? $(document).on("click", "button.options_buy",function(event) { // code for click event } $(document).on("change", "select.options_buy",function(event) { // code for chan ...

What is the best way to fix the "Module not detected: Unable to locate [css file] in [directory]" error when deploying a Next.js website on Netlify?

Trying to deploy my site on Netlify from this GitHub repository: https://github.com/Koda-Pig/joshkoter.com, but encountering an error: 10:02:31 AM: Module not found: Can't resolve '../styles/home.module.css' in '/opt/build/repo/pages&ap ...

What is the process for transferring a file's contents to my server?

I am currently working on allowing users to import an OPML file that I parse server-side in my Rails application. However, I am facing difficulties as it appears that my server is not receiving the information correctly (neither the success nor error funct ...

Using Javascript, Google Charts is able to interpret JSON data

I am currently working on integrating Google Charts and populating it with data from an external JSON file that I have generated using PHP's json_encode() function. After some effort, I managed to get Google Charts to display data successfully, but f ...

The request to the route timed out after waiting 5000ms for a response from the server

I am a newcomer to using Cypress and I'm exploring an HTML page for testing purposes. My goal is to test the login authentication and log the body of an XHR. Here's the test code I wrote for this: describe('Login test', function () { ...

Obtain asynchronous state in VueJS without the need for intricate v-if conditions

I am working on an application that heavily relies on Vue-Router and Vuex for state management. Within the Dashboard component, important user information is displayed. This data is fetched asynchronously from a database by Vue and then stored in Vuex. T ...

Jquery submenu accordion toggles open and closed with each click

My website has a hamburger menu with an accordion-style submenu implemented using jQuery for devices 1084px and smaller. For larger devices, the menu utilizes a hover-style submenu on desktop. However, I encountered issues when trying to use both the hove ...

How can we verify that the client has successfully completed the file download process?

I am currently working with a single large file. My goal is to accomplish the following tasks: 1) Upload the file to the server 2) Automatically delete the file from the server once it has been successfully downloaded by the user. Is there a method to ...

Stop jQuery from submitting the form in case of validation errors

Hey there, I'm currently working on preventing the AJAX form submission function from happening if one of the inputs fails validation. Edit: Specifically, I'm looking for guidance on what changes need to be made in //Adult age validation and var ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

How to maintain the selected value in a Vue.js dropdown even after the page is refreshed

When a user selects a value from a dropdown, it is pushed to the URL. If the page is refreshed, the dropdown should default to the selected value in the URL. This functionality is being implemented in Laravel. I have attempted the following approach, but w ...

methods for eliminating duplicate values from distinct genres

By clicking on the link provided, you will be able to view the code. The issue arises when I click on the action checkbox as it removes redundant data. However, if I then click on another checkbox, such as family, it will display the value. Interestingly, ...

ReactJS - Experiencing an abundance of re-renders in Protected Route

I have recently started working with React and encountered an issue with my Protected routes. They are functioning perfectly on my local machine but throwing errors on the server. You can see the error https://i.sstatic.net/l6dZW.png Below is my code: Pr ...

What are some ways to optimize Ajax requests for improved speed when multiple identical requests are made on a single webpage?

When the webpage is loaded, a block is dynamically created using an Ajax call to retrieve data from another page. This structure is then populated and added to a specific DOM element. However, multiple Ajax calls during page loads are causing delays. Is ...

AngularJS - Introducing blurred delay

Here is the code snippet I am working with: <div class="staff"> <input ng-model="user" ng-focus="isFocused = true;" ng-blur="isFocused = false;/> <div class="matches" ng-if="isFocused"> <div ...

Preventing Prepend Scroll: Tips and Tricks

Adding extra content to the top of the body can be frustrating, especially if it pushes everything down as you're trying to read. Is there a way to smoothly prepend this additional content without shifting the page layout, so that it seamlessly appear ...

Utilizing jQuery datepicker to extract data from a database and trigger an Alert: A tutorial

I want to create an alert that pops up when someone chooses a specific date on a calendar. The information displayed in the alert needs to be retrieved from a database, not just showing the selected date. I have been able to display a basic alert, but I ...

Having trouble customizing the Material UI button in React?

For a recent project, I utilized the older version (v1) of Material UI to ensure compatibility with Node 10.8. In order to implement a round button, I referred to this demo. The round mini button functioned perfectly without any applied themes. <Button ...