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

Best event for Angular directive to bind on image onload

I'm currently working on incorporating this particular jQuery plugin into my Ionic application. Although I have a good grasp of creating an Angular directive to encapsulate the plugin, I am encountering difficulties in successfully implementing it. B ...

Transmit information using the buttonRenderer feature in Ag-Grid for Angular applications

Struggling to transfer data between two unrelated components by clicking on a cell in ag-Grid and passing the data to a form component. I utilized the buttonRenderer function to extract row data from ag-Grid, but I'm unsure how to pass it to the secon ...

The script functions perfectly in jsfiddle, yet encounters issues when used in an HTML

I stumbled upon a seemingly peculiar issue with my script in jsfiddle: https://jsfiddle.net/oxw4e5yh/ Interestingly, the same script does not seem to work when embedded in an HTML document: <!DOCTYPE html> <html lang="en"> <head> & ...

What could be causing the Multer error in my Express.js application when attempting to upload a file for the second time, even though the first time was successful?

Whenever I try to upload a single file, the code works flawlessly. However, if I attempt to upload another file, I encounter the following Multer error: Error code: 'LIMIT_UNEXPECTED_FILE', field: 'myFile', storageErrors: [] To succes ...

How to use action cable to broadcast chat messages exclusively to targeted chat rooms in Rails 5

My current setup includes a Rails 5 application serving as the back-end, referred to as the "Core," and an Angular 1.6.4 application as the front-end, known as the "Front." These two applications operate on completely different domains. The goal is to int ...

Encountering status code 0 when handling 413 (Request Entity Too Large) error in AngularJS with Loopback API

1. Revealing Some Details In my client-side application built with AngularJS 1.3.15, I am utilizing a loopback API for handling requests. Within the application, I have set up interceptors using $httpProvider.interceptors to interpret status codes and di ...

Dealing with error handling in NUXT using asyncData and Vue actions

The URL I am trying to access is http://mywebsite.com/[category that doesn't exist]. Despite the code snippet provided below, I am unable to reach the catch block in asyncData. async asyncData({ params, store }) { try { await store.dispatch(&ap ...

Show data in a popup using jQuery DataTables and loading content asynchronously via Ajax

I am attempting to display a list in a popup based on an Ajax request. Prior to the Ajax call, the list is contained within the popup. However, after the Ajax request, the list remains on the page instead of inside the popup, and the old list still appears ...

"Exploring the power of asynchronous operations in NodeJS using Q

Currently, I am utilizing Node.js and I aim to incorporate promises to ensure a complete response following a for loop. exports.getAlerts = function(req,res,next){ var detected_beacons = []; if (!req.body || Object.keys(req.body).length == 0) { res.s ...

How do AngularJS promises get resolved?

Once a promise is resolved, will the code inside the .then block be executed in parallel, or does the current execution halt until the then block is executed before resuming from where it left off? ...

Exposure to vulnerabilities in react-scripts

While working on my ReactJS app, I encountered a challenge related to vulnerability and security issues. The use of react-scripts library has highlighted numerous vulnerabilities in the latest version. Is it possible for me to directly update the depende ...

When the link_to element is clicked, use AJAX to replace the content of a specific

I was wondering about a modification to the link in view/users/show: <%= link_to "Photos (#{@user.photos.count})", user_path(@user), id: "photo_link", remote: true %> My goal is to dynamically change [1..6] to [1..-1] without having to rerender the ...

Exploring the methods for testing $scope within an AngularJS controller

Is there a way to test the $scope object of my controller? Can I access the actual data that was assigned to it? I have set up my test like this, but when checking myScope, it shows undefined. 'use strict'; describe('myApp.view1 module&a ...

Can you effectively link together AngularJS promises originating from various controllers or locations?

Attempting to explain in as much detail as possible, the configuration file config.js contains the following code snippet: .run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $loca ...

How can cookies be managed with JavaScript, Express.js, or Node.js?

Could anyone advise on the optimal approach for managing cookies - through Express.js, Node.js, or client-side JavaScript/jQuery? I'm feeling a bit uncertain about security implications. Your assistance and insights are greatly appreciated. ...

Use PHP to highlight the row that has been selected in an HTML table

I am currently working on a project where I have styled multiple HTML tables on my website using alternating gray and white bands. Now, my goal is to highlight the selected row in a darker shade of gray. I have experimented with various solutions, and the ...

The history.push function seems to be leading me astray, not bringing me back

Issue with History.Push in Register Component App function App() { const logoutHandler = () =>{ localStorage.removeItem("authToken"); history.push("/") } const [loading, setLoading]= React.useState(true) useEffect(()=>{ ...

To close modal A in ReactJS using React-Bootstrap after opening modal B from modal A, follow these steps:

When the registration button is clicked, a signup modal appears. Is there a way to then open a login modal from within the signup modal, ensuring that the signup modal closes once the login modal pops up? show={this.props.signupModalOn} onHide={this.props. ...

Submitting a form using Ajax that was generated with the help of jQuery

Using a table with various rows, each row has an edit button. Upon clicking the edit button, a form is generated using ajax/json to populate the form data based on the selected row. An issue arises when setting up the ajax for this form. Although the met ...

jQuery: Implementing a function for all elements, including those dynamically loaded through Ajax later on

I have implemented a jQuery function to resize text areas, but I need it to work on all text areas. The function works well for existing text areas: $(document.ready(function(){$("text_area").resizer('250px')}); However, it fails to resize tex ...