Amcharts does not display the percentage value

I've been working on creating a bar graph using amcharts and I'm trying to show the percentage on top of each bar. Here is the code snippet I have so far:

$.ajax({
    url: "https://daturl",
    contentType: "application/json; charset=utf-8",
    type: "GET",
    dataformat: "JSON",
    async: false,
    success: function (data) {
        var amc = AmCharts.makeChart("chartdiv",
        {
            "type": "serial",
            "dataProvider": data,
            "categoryField": "name",
            "startDuration": 1,
            "categoryAxis": {
                "gridPosition": "start"
            },
            "trendLines": [],
            "graphs": [
                {
                    "valueField": "count",
                    "fillColors": "#0095cc",
                    "type": "column",
                    "balloonText": "[[title]] of [[category]]:[[value]]",
                    "fillAlphas": 0.8,
                    "lineAlpha": 0.2,
                    "id": "AmGraph-1",
                    "title": "graph",
                    "labelText": " ",
                    
                    //code for calculating percentage
                    "labelFunction": function (item, data) {
                        var total = 0;
                        console.log(data.length + " is the size of the data in long trips");

                        for (var i = 0; i < data.length; i++) {
                            total += data[i][item.graph.valueField];
                        }

                        var percent = Math.round((item.values.value / total) * 1000) / 10;
                        return percent + "%";
                    }
                }],
            "guides": [],
            "valueAxes": [
                {
                    "id": "ValueAxis-1",
                    "title": "Count",
                    "gridColor": "#FFFFFF",
                    "gridAlpha": 0.2
                }
            ],
            "categoryAxis": {
                "title": "Zone",
                "gridPosition": "start",
                "gridAlpha": 0,
                "tickPosition": "start",
                "tickLength": 20,
                "labelRotation": 24
            },
            "gridAboveGraphs": true,
            "allLabels": [],
            "balloon": {},
            "legend": {
                "enabled": true,
                "useGraphSettings": true
            },
            "titles": [
                {
                    "id": "Title-1",
                    "size": 15,
                    "text": "graph"
                }
            ]
        });
    },
    error: function () {
        alert("error while plotting down graph ");
    }
});

When I run the code, the graphs display correctly but the percentages are showing up as NaN. Any insights would be greatly appreciated.

Answer №1

The utilization of the labelFunction is not correct in your code. The documentation indicates that the parameters provided are a reference to GraphDataItem and the formatted label text.

Within your for-loop, you are attempting total += " "[0]["value"], leading to total += undefined and resulting in total being NaN. This inconsistency causes incorrect labels to appear on the graph.

To resolve this issue, it is recommended to access the complete dataSet using item.graph.data to perform accurate calculations.

Alternatively, I suggest relocating the for-loop to a different section of your script. By continuously summing up the data values each time the graph is redrawn, your loop executes multiple times unnecessarily when resizing the graph. Calculating the total sum once and utilizing it in the labelFunction would improve efficiency.

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

Personalized jQuery Slider with automatic sliding

I am currently working on creating my own image slider without relying on plugins. 1st inquiry : How can I achieve horizontal animation for the slider? 2nd inquiry : I want the images to cover both the height and width of their container while maintainin ...

Issue: The jQuery function with the ID jQuery1830649454693285679_1359620502896 did not receive a JSON

After going through numerous Q&As on the same problem, I couldn't find a solution specific to my issue. The situation involves a PHP script that outputs a JSON string: header('Content-Type: application/json'); echo $result; Here is th ...

ExpressJS exhibits unique behavior based on whether the API is requested with or without the specified PORT number

I have encountered an issue with my 2 flutter web apps. One of them is functioning flawlessly when I request the URL, but the other one only works when I include the port xxxxx:4000/nexus-vote. However, when I remove the port, I receive a status code of 20 ...

How can the first paragraph value of a div be found using jQuery in Next.js?

How can I retrieve the value of the first <p> tag within my div when a button inside the same div is clicked? Despite attempting to use $(this), it doesn't appear to be functioning as expected. Take a look at the code snippet below: <div cla ...

Solutions for accessing data variables outside of a Vue file

Utilizing Vue.js for data binding and filtering has been a rewarding experience. I've set up a Vue object within a .js file and now I aim to pass external data into it. Let's take a look at my test object testFile.js: var vm = new Vue({ el: ...

The importance of understanding Req.Body in NODE.JS POST Requests

Currently, I am developing a Node.JS application that interacts with a MySQL database. The app retrieves data from the database and displays it in a table using app.get, which functions correctly. The issue I am facing is that when utilizing app.post, re ...

Is it necessary to test the main.js file in Vue.js project?

While performing unit tests on components is acceptable, after running coverage analysis I have noticed that certain lines of code in the main.js file remain uncovered. This raises the question: should the main.js file also be included in testing? Specifi ...

NPM encountered an issue that prevented it from scanning directories due to a permission denial with the error code E

Whenever I type "npm run build:prod" build:prod npm run build -- --configuration production --aot --optimization=false I encounter the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e4e3ece1fbafece3 ...

When attempting to print the content inside a Bootstrap modal, the display does not appear but instead a blank page is printed

My goal is to print the text content of a bootstrap modal while leaving space for images blank when clicking the print button located within the modal. Unfortunately, upon clicking the print button, I am only getting a blank page without any content displ ...

Synchronizing the call of various views in an Angular application

I'm currently working on an angular single page application with a specific structure in mind. "app.parent - main parent state" "app.parent.childState - child state" "app.parent.childSatate" includes 4 different named views. My goal is to display so ...

The compatibility between an Ajax client and a Django server across different domains is only possible when using JSONP

Currently, our Django application is functioning on tomcat with Basic Authentication. I am interested in making cross-domain requests, and have found that it only works when using $.ajax({...dataType: 'JSONP',...}). The use of dataType: JSON does ...

Issues with CSS Modules not applying styles in next.js 13 version

Employing next.js 13.1.1 along with /app Previously, I had been handling all of my styles using a global.css, however, I am now attempting to transition them into CSS Modules. Within my root layout.js, there is a Header component that is imported from ./ ...

Mouse over effect to highlight the crosshair on a table

My code currently enables a crosshair function, but I am looking for a way to limit the highlight effect only within the cursor (hover) area. Instead of highlighting in a "cross" shape, I would like it to show a backward "L" shape. This means that the hig ...

Analyzing DynamoDB Query

I am on a mission to recursively analyze a DynamoDB request made using the dynamo.getItem method. However, it seems that I am unable to locate a similar method in the DynamoDB SDK for Node.js. You can find more information about DynamoDB SDK at http://do ...

Enhance the current MultiSelect object by incorporating JQuery MultiSelect

Is there a way to detect changes on a JQuery MultiSelect in order to trigger an update elsewhere? The typical javascript onchange method does not seem to work because the select itself does not change. However, I came across a method called "beforeclose" t ...

Asynchronous jQuery AJAX calls are now obsolete and deprecated

Currently, I am utilizing jquery version 1.11.2 and attempting to perform an asynchronous ajax call for form validation purposes. Below is the code snippet: <form name="form1" id="form1" method="post" action="/payment/payment.php" onsubmit="retur ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

What is the best way to incorporate the value of a textbox into a list?

I currently have a list structured like this: <p>Please choose from the following options:</p> <script type="text/javascript"></script> <select id='pre-selected-options1' multiple='multiple'> <opt ...

Why aren't Material UI v5 styles being applied to the class?

I have been attempting to customize the MUI slider by applying styles using the className prop. However, I am facing an issue where the styles assigned to the main class are not being applied, but other styles such as the 'hover' state are workin ...

Sending arrays from HTML table rows to a JavaScript function

When developing a dynamic table using Javascript, I am able to add rows programmatically with the following function: function addrow(tableid) { var tablename = document.getElementById(tableid); var rows = tablename.rows.length; if (rows < ...