Open In App

Chart.js New Axes Developer

Last Updated : 13 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Chart.js New Axes are used to extend and create custom axes by using the Chart.Scale class. Using this feature we can develop specific scales other than the standard one which is provided by Chart.js.

Syntax:

class MyScale extends Chart.Scale {
// Your custom scale extensions...
}
MyScale.id = 'myScale';
MyScale.defaults = defaultConfigObject;

Custom Scale Properties

  • Positioning Properties: left, right, top, bottom, width, height.
  • Margin Properties: margins (with left, right, top, bottom).
  • Padding Properties: paddingLeft, paddingRight, paddingTop, paddingBottom.

Custom Scale Interface

  • determineDataLimits(): Sets this.min and this.max based on data.
  • buildTicks(): Generates tick marks.
  • getLabelForValue(value): Returns the label for a given value.
  • getPixelForTick(index): Returns the pixel for a tick mark.
  • getPixelForValue(value, index): Returns the pixel for a value.
  • getValueForPixel(pixel): Returns the value for a pixel.

Utility Functions

  • isHorizontal(): Checks if the scale is horizontal.
  • getTicks(): Returns the scale’s tick objects.

CDN Link:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Example 1: In this example, it shows the data values as percentages out of 100 rather than absolute numbers.

HTML




<!DOCTYPE html>
<html>
 
<body>
    <canvas id="myChart"></canvas>
 
    <script src=
    </script>
 
    <script>
        // Define percentage scale class 
        class PercentageScale extends Chart.Scale {
            // Constructor
            constructor(cfg) {
                super(cfg);
                this._startValue = 0;
                this._endValue = 100;
            }
 
            // Determine the data limits (mandatory)
            determineDataLimits() {
                this.min = this._startValue;
                this.max = this._endValue;
            }
 
            // Build ticks (mandatory)
            buildTicks() {
                this.ticks = []; // Initialize tick array
                for (let i = this.min; i <= this.max; i += 10) {
                    this.ticks.push({ value: i });
                }
            }
 
         
            generateTickLabels(ticks) {
                ticks.
                    forEach(tick => tick.label = `${tick.value}%`);
            }
 
            // Calculate pixel for value (mandatory)
            getPixelForValue(value) {
                const pixel =
                    (value - this.min) /
                    (this.max - this.min) *
                    this.width;
                return this.isHorizontal() ? pixel : this.bottom - pixel;
            }
 
            // Calculate value for pixel (mandatory)
            getValueForPixel(pixel) {
                const value =
                    this.min + (pixel / this.width) * (this.max - this.min);
                return this.isHorizontal() ? value : this.bottom - value;
            }
        }
 
        // Set id for the custom scale
        // The id should match the type in the chart config
        PercentageScale.id = 'PercentageScale';
        // Default settings
        PercentageScale.defaults = {};
 
        // Register the custom scale
        Chart.register(PercentageScale);
 
        // Create chart instance
        new Chart('myChart', {
            type: 'bar',
            data: {
                labels: ['A', 'B', 'C'],
                datasets: [{
                    label: 'Dataset 1',
                    data: [1125, 2500, 750],
                    backgroundColor: ['rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)'], // Optional colors
                }]
            },
            options: {
                scales: {
                    y: {
                        type: 'PercentageScale'
                    }
                }
            }
        });
    </script>
</body>
 
</html>


Output:

Screenshot-2023-12-07-015919

Example 2: In this example, the y-axis values are displayed as percentages instead of absolute numbers. It illustrates the customization of chart scales in Chart.js, specifically showing how to format y-axis labels with a percentage sign.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>Custom Scale in Chart.js</title>
    <script src=
      </script> <!-- Including Chart.js -->
</head>
 
<body>
 
    <!-- Canvas element for the chart -->
    <canvas id="myPercentageChart"
            width="400"
            height="300">
      </canvas>
 
    <script>
 
        // Create a bar chart with a custom
        // scale in the options
        const ctx = document
            .getElementById('myPercentageChart')
            .getContext('2d');
        const myBarChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Red', 'Blue',
                         'Yellow', 'Green',
                         'Purple', 'Orange'],
                datasets: [{
                    label: 'Percentage of Votes',
                    data: [12, 19, 3, 5, 2, 3],
                    backgroundColor: 'rgba(0, 123, 255, 0.5)',
                    borderColor: 'rgba(0, 123, 255, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        ticks: {
                            // Custom tick formatting to show as percentages
                            callback: function (value, index, values) {
                                return value + '%';
                            }
                        }
                    }
                }
            }
        });
    </script>
 
</body>
 
</html>


Output:

Screenshot-2023-12-09-124649



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads