Leveraging Datalabels and ChartJS in combination with Chartjs-node-canvas

Using NodeJS in conjunction with ChartJS, I am able to render graphs directly to a file successfully.

This is achieved by installing the npm module ChartjsNodeCanvas.

To display labels on the graph, I utilize the official ChartJS plugin ChartJS-plugin-datalabels

However, it seems like the Canvas module has a different way of activating ChartJS plugins and it is likely that I am not activating the datalabels plugin correctly. As a result, the labels are not being displayed on the graph.


const Chart = require('chart.js');
const datalabels = require('chartjs-plugin-datalabels')
const { CanvasRenderService } = require('chartjs-node-canvas');

const width = 600;
const height = 400;
const chartCallback = (ChartJS) => {

    ChartJS.defaults.global.elements.rectangle.borderWidth = 2;
    ChartJS.plugins.register({
        datalabels
    });
};

const canvasRenderService = new CanvasRenderService(width, height, chartCallback);

(async () => {
    const configuration = {
        type: 'bar',
        data: {
            datasets: [
                {
                    type: "bar",
                    barThickness: 24,
                    label: 'My dataset',
                    data: ydata['data'],
                    backgroundColor: 'rgba(75,192, 192, 0.2)',
                    borderColor: 'rgba(54, 162, 135, 0.2)',
                    borderWidth: 1,
                    datalabels: {
                        align: 'start',
                        anchor: 'start'
                    }
                }, 
                labels: xdata,
            }

        options: {
            scales: {
                yAxes: [
                    {
                        id: 'left-y-axis',
                        position: 'left',
                        stacked: false,
                        ticks: {
                            beginAtZero: true,
                            callback: (value) => value + "R"
                        },
                    },
                    {
                        id: 'right-y-axis',
                        position: 'right'
                    }
                ],
                xAxes: [{
                    stacked: true,

                }]
            },
            plugins: {
                datalabels: {
                    backgroundColor: function(context) {
                        return context.dataset.backgroundColor;
                    },
                    borderRadius: 4,
                    color: 'red',
                    font: {
                        weight: 'bold'
                    },
                    formatter: Math.round
                }
              }
         }
    };
    const image = await canvasRenderService.renderToBuffer(configuration);
    fs.writeFileSync(tgMsgPath+"test.png", image)        
})();

The chart is displayed but unfortunately no labels appear on the graph.

Answer №1

Here is a method to enable plugins using ChartJs-node-canvas:

const chartJsFactory = () => {
const Chart = require('chart.js');
require('chartjs-plugin-datalabels');
delete require.cache[require.resolve('chart.js')];
delete require.cache[require.resolve('chartjs-plugin-datalabels')];
return Chart;
}

// ...

const canvasRenderService = new CanvasRenderService(
  chartWidth,
  chartHeight,
  chartCallback,
  undefined,
  chartJsFactory
);

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

The ID update functionality in Node.js is malfunctioning

Hello everyone, I am currently venturing into the world of NodeJS with a goal to create a backend API for a car rental agency. After writing some code to update, view, and delete records by id stored in MongoDB, I encountered a strange issue where it only ...

Steps for ensuring a promise is fulfilled in Node.js and Firebase

I've been struggling with this issue for quite some time now and can't seem to figure it out. g_globalList.once("value").then(function(tickList){ var multiPaths = []; tickList.forEach(function(ticker){ ticker.val().forEach(fu ...

AngularJS - Greetings global

Currently experimenting with AngularJS, however I noticed that the official tutorial provides download code and predefined npm dependencies without explaining how to create it from scratch. I am using Linux (Mint Mate 17) with Node.js / npm / bower instal ...

Discovering the most recent version of a package on npm

Is there a way to display the most recent version of a module using npm? I would like to see something along the lines of npm --latest express that will show v3.0.0. ...

Error encountered while trying to install eslint-plugin-react with an incompatible engine

Hello, I am a new React user and I am running into an issue in my terminal after installing eslint-plugin-react and eslint-plugin-react-hooks. npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '@es-joy/<a href="/cdn-cgi/l/emai ...

Error: The function "execute" has not been declared

Hey there! I've created a Discord bot that is meant to check the status of a Minecraft server, but I'm encountering an issue with the embed. It's showing this error: UnhandledPromiseRejectionWarning: ReferenceError: execute is not defined. ...

Retrieve all records in which a Sequelize association uses hasOne

Currently, I am exploring the `sequalize association - hasOne` feature. However, I encountered an unexpected issue where all the rows from the `USER` table are being returned instead of just the rows from the `system_admin` table. Is this the intended beha ...

Having issues with Sequelize and SQLite auto increment functionality. No errors when using AutoIncrement, but the auto increment feature is not working. On the other hand, errors arise when using

I am currently in the process of developing a discord bot, which includes 2 slash commands. One command is called /setup, used for adding the guildId and an adminChannel to a database. The other command is named /onduty, which is used for adding the user, ...

In Node.js, JSONWebToken have no expiration date

My issue revolves around the jsonwebtoken, specifically when I generate a token using jwt.sign(data, secret, {expiresInMinutes: 30}); Upon decoding this token, I notice that it lacks the elements exp and iat. All I can see is the data without any indicati ...

String found at position 22 in JSON was not anticipated

Error: Unexpected character in JSON at position 22. I am stuck, can someone assist me with this issue? Here is the content of my package.json file: { "name": "restful-api", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "tes ...

The only information returned from calling mongoose's Model.save() method are the fields { _id, __

I've encountered a problem even though I believe I'm following all the right steps. I'm attempting to save an item from a form into my mongodb collection using mongoose. This is what my schema looks like: // stationmodel.js export const Sta ...

Error: Unable to access undefined properties (specifically 'create') while using Sequelize in an Express.js and Node.js environment

Below is the snippet of my code Project Structure backendstuff (the express app) - models/currentweather.js - models/sequelize.js - routes/weather.js app.js models/currentweather.js const { Sequelize, DataTypes, Model } = require('sequelize'); ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

Having trouble resolving a dependency within an imported node module named "node-fetch"

As someone who is still a bit of a novice in Node, I apologize for what may seem like a beginner question. I have developed a small Chrome extension where the only node module I imported is called node-fetch. Typically, running yarn build to create a packa ...

Sequelize is unable to retrieve a table from the database

I am configuring Sequelize in order to streamline the manipulation of an MSSQL database. My attempt to define a table called 'Stock' has resulted in unexpected behavior when trying to query it. Below is the code snippet I used for defining the t ...

There was a hiccup encountered while trying to follow the steps for creating a

Despite others' attempts to solve the errors quickly, the search continues and the symptoms persist. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="046c6168686b29766165677044342a352a34">[email protected]< ...

The class function in the exported typescript logs that "this" is not defined

I am currently facing an issue with my TypeScript class where I am setting class values in a constructor and referencing them using "this" in a class method. While the .ts file compiles without any warnings, when I import the compiled .js file into another ...

What is the best way to incorporate HTML code into a view?

Currently utilizing express.js along with EJS as the chosen template engine. I'm running into confusion when attempting to integrate partials into my project. The examples I've come across use the JADE template engine, which has left me uncertain ...

Determine the absolute path with respect to a different reference path, rather than the current working directory

One of the challenges I'm facing with my Node.js module is how to easily allow developers to edit the location of the dependencies relative to the module file itself. The issue arises because the current working directory, accessed through `process.cw ...

Having trouble accessing req.user on my Node.js server using Auth0 and Angular

Currently, I am utilizing auth0 for my admin panel's login system and it is functioning smoothly. However, I have encountered an issue in node where 'req.user' is returning as undefined for some unknown reason. This setup is fairly basic; I ...