Utilize Chart.js to showcase vertical axis labels on a line chart

Is there a way to include a Y-axis label for a line graph created using chart.js and angular-chart.js?

I am looking to add a y-axis label to my graph.

HTML
<ion-content ng-controller="AgeController">
<canvas id="line" class="chart chart-line" data="data"
  labels="labels" legend="true" series="series"
  click="onClick" colours="['Red','Yellow']" width="402" height="201" style="width: 402px; height: 201px">
</canvas> 
</ion-content>

JS

app.controller('AgeController', ['$scope','$http',function($scope,$http) {    

           $scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
  $scope.series = ['Series A', 'Series B'];
  $scope.data = [
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90]
  ];

                }]);   

Answer №1

The general consensus regarding the axis title is to position it outside of the canvas, as mentioned in this discussion thread here. However, considering the ongoing discussions on a related issue found here, this approach may be subject to change.


Integrating a Y Axis Title

Nevertheless, here's how you can implement an axis title within the current version using the canvas element. To begin with, extend the chart functionality to accommodate the display of the axis title (largely inspired by techniques discussed in this Stack Overflow thread)

Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function (data) {
        // Adjusting label width for the title
        if (this.options.yAxisLabel)
            this.options.scaleLabel = '         ' + this.options.scaleLabel;

        Chart.types.Line.prototype.initialize.apply(this, arguments);

        if (this.options.yAxisLabel)
            this.scale.yAxisLabel = this.options.yAxisLabel;
    },
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);

        // Rendering the title
        if (this.scale.yAxisLabel) {
            var ctx = this.chart.ctx;
            ctx.save();
            // Text alignment and color
            ctx.textAlign = "center";
            ctx.textBaseline = "bottom";
            ctx.fillStyle = this.options.scaleFontColor;
            // Positioning
            var x = this.scale.xScalePaddingLeft * 0.2;
            var y = this.chart.height / 2;
            // Adjust origin
            ctx.translate(x, y);
            // Rotate text
            ctx.rotate(-90 * Math.PI / 180);
            ctx.fillText(this.scale.yAxisLabel, 0, 0);
            ctx.restore();
        }
    }
});

If you are utilizing Angular-Chart.js, register the new chart type as follows

angular.module('chart.js')
    .directive('chartLineAlt', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('LineAlt'); }]);

Then, pass in the axis title through the options like so

...
$scope.options = {
    yAxisLabel: "My Y Axis Label",
}

Incorporate it into your markup

<canvas id="line" class="chart chart-line-alt" data="data"
        labels="labels" legend="true" series="series" options="options"
        click="onClick" colours="['Red','Yellow']" width="402" height="201" style="width: 402px; height: 201px"></canvas>

Note the inclusion of the options attribute and the altered class value to chart-line-alt


Fiddle Example - http://jsfiddle.net/eeqfvy6f/

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

Guide on invoking Objective-C function from JavaScript on iOS

I'm currently working on integrating Highchart into an iOS app. I have a requirement where I need to pass values from JavaScript (HTML file) to an Objective-C method. For example, when a user zooms in on the chart displayed in a UIWebView using Highch ...

Create a row in React JS that includes both a selection option and a button without using any CSS

My dilemma involves a basic form consisting of a select element and a button. What I want to accomplish is shifting the position of the form to the right directly after the select element Below is the code snippet that I have: return ( <> <div ...

HTML Menu with Ajax functionality designed to work seamlessly without relying on JavaScript

I'm working on making my navigation system compatible with both clients who have JavaScript disabled and those who can use Ajax. Currently, I have dynamic links generated inside the navigation like "index.php?page=/cat/page.php". <li id="sidebarit ...

combine two 2D arrays in JavaScript

I am facing a challenge with this issue concerning 2D arrays. The task at hand is to create a JavaScript function called addArrays(al, a2) that accepts two 2D arrays of numbers, a1 and a2, and calculates their "sum" following the matrix sum concept. In oth ...

Conceal a form depending on the referer_url parameter

I am looking to customize my 404 page by displaying a small form only when the visitor comes from a website, not from an email link or directly entering the URL. The purpose of this form is to address broken links that led the visitor to the error page. If ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

I possess multiple checkboxes that appear as described below. I am looking to modify the nested value highlighted in the blue circle in the image

I need to make a change in this area of my state: view screenshot The specific portion highlighted in the circle is what I want to modify **Here is my checkbox input code:** {this.state.data.map((elm) => ( <div className={classes.rowContainer}&g ...

How can models effectively communicate with each other in AngularJS?

In my application, I have a navigation module that contains details (NavigationModel). There are also modules (SubCtrl1, SubCtrl2..) that can be selected from the Navigation part (NavigationCtrl). Each module has its own model with different properties, so ...

Displaying MySQL information on an EJS document including references to other tables

Check out the project on GitHub I am currently working on retrieving quiz answers from a MySQL database and displaying them in a form using EJS templating within a node.js/express application. However, I am facing challenges with correctly mapping answers ...

Assistance in using jQuery to locate specific div elements is

I am currently working on creating a navigation bar that features icons triggering contextual submenus upon hover. The main idea is that hovering over an icon will display a popup menu or tooltip with additional options, while still allowing the icon itsel ...

Steps for assigning an id to a newly created div within a parent div while in design mode

Imagine creating a div element with the attribute contenteditable="true", and then checking the console for what happens next: 1st. In the console, you only see a simple div tag. <div id="typbody" contenteditable="true" style="width:100%; height:200px ...

Cross-domain scripting with JavaScript

I currently manage 2 subdomains securityservices.example.com workstations.example.com All workstations are associated with the workstations.example.com One of the workstations, known as WS789012 on the domain, is fully qualified as: WS789012.workst ...

Do we require Node JS for developing Angular JS applications? If so, what is the rationale behind it? And why is Node JS not needed in a production environment?

Do you need Node.js to develop an AngularJS application? If so, what is the reason for that requirement? I have come across some articles stating that Node.js is necessary when building an AngularJS app, however, it is not needed in production. I am puzzl ...

Show the button's value in the textbox and update the selected button's color using JavaScript

I am having difficulty changing the background color of a selected button after displaying its value in a textbox. The code below successfully displays the button value in the textbox, but I can't figure out how to change the background color of the s ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

What are some ways to enhance the opacity of a Material UI backdrop?

I'm looking to enhance the darkness of the material UI backdrop as its default appearance is not very dark. My goal is to make it dimmer and closer to black in color. ...

Tips for avoiding the display of concealed forms on a webpage

Hey there, I'm just starting out with html forms and currently experimenting with Jquery to hide forms upon loading the page. However, I've encountered an issue where some forms briefly appear before hiding after the page finishes loading. Here& ...

What is the reason behind the failure of executing "this.$refs.inputField.focus()"?

I've set up an input field with a ref="inputField" as shown below: <input ref="inputField"> <button @click="btn">Click</button> When the button is clicked, I want the input field to receive focus. Here& ...

transferring data from JavaScript on the client side to Express on the server side

Using JavaScript, I have created the HTML DOM that you see in the code below. Now, my goal is to send the value of an input created in JavaScript to the server side. The server is built with node.js and express framework. Once the value is sent to the serv ...

Is there a way to retrieve the title, description, and image URL of a URL through Ajax, similar to how Facebook shares a link?

Currently, I am developing a project that involves allowing users to submit a URL. The system will then extract the title, images, and description from the provided URL and offer the option to toggle between different images. Upon submission, these extrac ...