Tips for converting the Y-axis values in Chart.js from numerical to string format

Currently, I am utilizing Chart.js and facing an issue with modifying the y-axis (refer to the screenshot below). My attempt to populate the yLabels property with a string array was unsuccessful. Any guidance on this matter would be highly appreciated!

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

 jQuery(document).ready(function($) {
    'use strict ';
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ["HTML", "CSS", "SCSS", "JavaScript"],
            yLabels: [
                'newb',
                'codecademy',
                'code-school',
                'bootcamp',
                'junior-dev',
                'mid-level',
                'senior-dev',
                'full-stack-dev',
                'famous-speaker',
                'unicorn'
            ],
            datasets: [{
                data: [12, 19, 3, 10],
                backgroundColor: [
                    'rgba(255, 159, 64, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(255, 206, 86, 0.2)'

                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)'

                ],
                borderWidth: 1
            }]
        },
        options: {
            legend: {
                display: false
            },
            
            title: {
                display: true,
                text: 'Shameless Bar Graph showcasing skill proficiency'
            }
        }
    });
});

Answer №1

If you're working with version 2.x of the chart, keep in mind that the yAxes labels are stored in the options rather than the data.

A helpful resource can be found in the documentation, guiding on how to customize tick formats using the callback attribute within options.scales.yAxes.


To achieve your desired outcome, add a JavaScript object to your code like this:
// Assign specific values for corresponding keys
var yLabels = {
    0 : 'newb', 2 : 'codecademy', 4 : 'code-school', 6 : 'bootcamp', 8 : 'junior-dev',
    10 : 'mid-level', 12 : 'senior-dev', 14 : 'full-stack-dev', 16 : 'famous-speaker',
    18 : 'unicorn', 20 : 'harambe'
}

Then include the following in your callback:

options: {
    scales: {
        yAxes: [{
            ticks: {
                callback: function(value, index, values) {
                    // When the value/tick is 8
                    return yLabels[value];
                    // It will display 'junior-dev' on your chart
                }
            }
        }]
    }
}

Check out the result on this jsFiddle link.

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

Is there a way to adjust text animations so they appear separately in their designated space?

During my project, I decided to incorporate some CSS animations onto the site. However, I encountered a problem with the overflow: hidden attribute not functioning as anticipated. Here is the code snippet I used: .jumbotron { height: 100%; heigh ...

Encountering the error message "IE 11 ASP.NET Unable to retrieve property 'stringify' due to an undefined or null reference"

I am currently working on an ajax code that takes in 2 string parameters and passes those parameters to a C# method in the backend, which then updates the user record in a database. Here is the code snippet I have been working on: // Grabs the Customer_I ...

Leveraging ng-attr in dynamically added HTML elements through ng-bind-html

Have you ever wondered how ng-attr is evaluated for elements inserted using ng-bind-html? Check out this JS Fiddle demonstration. Here's the HTML: <body ng-app="TestApp" ng-controller="TestCtrl"> <div ng-bind-html='y | to_trusted&a ...

The <script> element failed to close correctly

Within my default.jspx file, which serves as the foundational layout for the page, I am attempting to import several jQuery libraries. The code snippet looks like this: <head> ... <spring:url value="/resources/js/lib/jquery-1.9.1.min.js" ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...

Set a string data type as the output stream in C++

I have a method called prettyPrintRaw that seems to format the output in a visually appealing manner. However, I am having trouble understanding what this specific code does and what kind of data it returns. How can I assign the return value of this code t ...

changing the core JavaScript of a keyboard plugin

To access the demo, click on this link: . You can find the main javascript file at https://raw.githubusercontent.com/Mottie/Keyboard/master/js/jquery.keyboard.js. Is there a way to switch the positions of the accept and cancel buttons? ...

Issue with implementing an if statement in a function using JQUERY

I have a function that detects changes in a checkbox. Upon page load, the checkbox may be checked or unchecked based on previous actions. I am looking to keep track of whether the checkbox has been modified. If the checkbox is changed and then changed bac ...

Run ajax function prior to changing location; status now marked as canceled

Imagine needing to redirect a page when a button is clicked: <div onClick="clickButton"></div> function clickButton(href) { // an HTTP post request is sent here, without a callback or then/done function sendSomeRequest() location.href ...

Tips for passing data to a child component from a computed property

Currently in the process of setting up a filter using vue-multiselect. Everything seems to be working fine, but there's one issue I can't seem to resolve. Upon page reload, the label (v-model) appears empty. The root cause seems to be that the v ...

Tips for avoiding performance bottlenecks in Polymer 1

Environmental Issue Polymer 1 Challenge: I am facing an issue where I have an Array containing 35 objects. When I use a dom-repeat template to create a list of elements (all identical), it takes around 10 seconds for all the elements to render. The ent ...

The blur feature in Tinymce isn't functioning properly when handling multiple editable textareas simultaneously

I am experiencing an issue with the Tinymce blur function not working correctly. I have multiple elements where Tinymce editor is being used. I am utilizing the dblclick event to edit a textarea, and everything works fine except for the blur event not trig ...

Iterate through JSON objects

Having an issue with looping through JSON using jQuery AJAX. Despite receiving the JSON data from PHP and converting it to a string, I'm unable to loop through it properly in JavaScript. In my for loop, I need to access $htmlvalue[i] to parse the data ...

What is the best way to apply conditional hovering in styled components?

Is there a way to customize the hover effect of a component based on specific props? I want the background to change when hovering over it if certain props are set, but do nothing if different props are specified. export const Container = styled.div` ...

Force a video element to play by using React Context Provider

I've been incorporating the React Context in a similar manner here, and I'm facing a challenge on how to update my video element (to play the video). Shouldn't the components automatically update when they receive the prop? Below is a simpl ...

Challenges with creating a contact form using bootstrap modal

I'm facing an issue with a bootstrap modal contact form. It works fine on all browsers except for iPad/Safari. Can anyone help me figure out what's wrong? On iPad, the modal is positioned to the right and down the page instead of in the cente ...

Limiting the display to only a portion of the document in Monaco Editor

Is there a way to display only a specific portion of a document, or in the case of Monaco, a model, while still maintaining intellisense for the entire document? I am looking to enable users to edit only certain sections of a document, yet still have acce ...

The "users" property or method has not been defined in Vue.js applications

During the development of my Vue.js shopping cart, I encountered an issue where I wanted to display the username in a label after the user provided correct information. However, I received the following error in Google Chrome: vue.js:634 [Vue warn]: Prope ...

Step-by-step guide on writing to a JSON file using Node.js

I am currently developing a Facial Recognition web application using React for the frontend and Node.js for the backend. You can find more information about my project here. So far, I have completed the frontend part where users manually add 128-d descript ...

Switching between boolean values based on another value in react is a common practice

When a user is chosen from the list, a boolean value becomes true. If the chosen user is then unselected, the boolean turns false. This boolean will stay true if another user is selected from the list. Here's the code snippet: import React, { useEffec ...