"Visualizing data with Highcharts: Utilizing percentages in a basic bar chart

I am working on a basic 1-series bar chart with nominal values for each bar. While I am able to plot it with data labels and axis showing the value of each bar, my goal is to display the percentage of the total series on these labels while keeping the nominal value in a tooltip upon hover (so I prefer not to convert the data to percentages before plotting).

Here's an illustration of what I want to achieve along with my current progress:

fiddle

This is how I currently set up the axis labels using the formatter function:

plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true,
                    formatter: function(){
                        return Highcharts.numberFormat(this.y,0);
                    }
                }
            }
        }

Is there a specific formatter variable that can help me accomplish this? I know pie charts allow for this easily, but I believe bar charts convey data more effectively.

EDIT: In simple terms, how can I calculate the sum of all points in the series? Once I have this, calculating the percentage becomes straightforward:

return Highcharts.numberFormat(100 * this.y / this.y.total,0) + "%";

where this.y.total represents the series total sum.

Answer №1

To determine the total, you must iterate through the dataset and obtain the sum. Afterward, utilize the datalabel formatter function to retrieve the percentage.

See an illustration below:

http://jsfiddle.net/ABC123/987/

formatter:function() {
  var percent = (this.y / dataSum) * 100;
  return Highcharts.numberFormat(percent) + '%';
}

update::

revised example showcasing axis labels:

http://jsfiddle.net/ABC123/988/

[[UPDATE regarding comments]]

When plotting percentage values for multiple series, several fundamental challenges may arise.

If you are computing the % of two distinct data series and exhibiting the % value despite plotting the raw value, your chart may lead to confusion and misinterpretation in most instances.

Directly depicting the data as percentage values is typically recommended in such scenarios, and if desired, you can incorporate the raw data value as an additional attribute in the point object for display purposes (e.g., http://jsfiddle.net/ABC123/989/)

If you are determined to employ the original method on two different series, you can create separate variables for calculation purposes and assess the series name within the formatter to ascertain which data sum to compute against.

Answer №2

After receiving insightful advice from @jlbriggs, I was inspired to develop a formatter function that dynamically updates data values. This function constantly tracks the current data, ensuring that any programmatically induced changes are promptly reflected in the percentages displayed. With the clever utilization of .map().reduce(), there is no need for cumbersome loops or manual calculations.

dataLabels: {
  enabled: true,
  formatter: function() {
    var pcnt = (this.y / this.series.data.map(p => p.y).reduce((a, b) => a + b, 0)) * 100;
    return Highcharts.numberFormat(pcnt) + '%';
  }
}

Answer №3

Give this a shot: percentageCalculation()

The method is well-detailed in the official highcharts documentation.

http://api.highcharts.com/highcharts#plotOptions.series.dataLabels.formatter

UPDATE

If you're working with non-stacked series, make sure to calculate the total values before plotting the graph... The following function will sum up all your values into one variable for use in your formatter function later on.

function calculateSum(arr)
{
  var total = 0;
  for (var i = 0, value; value = arr[i]; i++)
  {
    total += value;
  }
  return total;
}

Answer №4

The Highchart library offers a wide range of built-in functions that make chart customization easy. If you want to display numbers on the chart up to a certain decimal place, you can use the following function:

import {numberFormat} from 'highchart';

You can then format the number like this:

numberFormat(this.y, decimalPlaceToFormat)

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

implementing conditional logic in angularjs expressions

<p>{{isExisted}}</p> Looking to show either "Active" or "Inactive", but the isExisted variable only returns true or false. Need help with setting up a conditional if else statement to change it to the desired value. ...

Access the Windows directory through a custom HTML link

Currently, I am in the process of creating a personalized "website" that contains a collection of links leading to specific items on my computer. When I click on a link, the folder opens within the browser. Is there a way for these links to open Windows Ex ...

Concurrent programming in Node.js with the async module

Is it recommended to avoid utilizing multiple instances of an async module feature simultaneously? In my code, there are three parts that need to be executed in sequence. The structure of my code looks like this: var async = require('async'); a ...

Setting a completion flag using a factory in AngularJS

I'm struggling to create a factory that can set a completion flag for a value within an object. The object in question looks like this: {"key1":"value1", "key2":"value2", "key3":"value3"} My goal is to retrieve and operate on the value associated wi ...

Best practices for defining module-wide constants in AngularJS

In my project, I have around 20 "modules" each with its own unique functionality but following the same structure. These modules are stored in separate files within their respective folders. For instance, the admin module is located in the modules/admin fo ...

Utilize unshift() method in JavaScript to insert form input into an array

I'm having trouble with adding elements to an array using a form and the unshift() method. The code snippet provided below isn't functioning as expected, and I need help understanding why. <form> <input id="input"></input> < ...

Utilizing Node.js with Express and Swig to seamlessly pass a local JSON file to a template

I am new to working with nodes, and I have successfully managed to integrate Express/swig and display them on the screen. However, when I include my d3 code (which functions independently), I encounter an error in the console: Uncaught TypeError: Cannot re ...

The perplexing results received when using the npm outdated command

Could someone provide an explanation for the meaning behind this output? $ npm --version 3.10.8 $ npm -g outdated npm Package Current Wanted Latest Location npm 3.10.8 4.0.2 3.10.9 As stated in the documentation, the "Wanted" column should d ...

AJAX using PHP returns an object containing null values

As a beginner in ajax programming, I encountered a small issue. I created a function in jQuery that makes an ajax call to a PHP file, which then retrieves information about a player from the database. However, when the PHP file responds to the ajax functio ...

I'm looking to retrieve the selected value from my autocomplete box in React using the Material UI library. How can I

Here is a snippet of code that utilizes an external library called material ui to create a search box with autocomplete functionality. When a value is selected, an input tag is generated with the value "selected value". How can I retrieve this value in ord ...

"Enhancing User Experience with Hover States in Nested React Menus

I have created a nested menu in the following code. My goal is to dynamically add a selected class name to the Nav.Item element when hovering, and remove it only when another Nav.Item is hovered over. I was able to achieve this using the onMouseOver event. ...

Error: Firebase Cloud Functions reference issue with FCM

Error Encountered An error occurred with the message: ReferenceError: functions is not defined at Object. (C:\Users\CROWDE~1\AppData\Local\Temp\fbfn_9612Si4u8URDRCrr\index.js:5:21) at Module._compile (modul ...

How to retrieve JSON data from unidentified objects using JQuery

I have made an AJAX call and received a JSON file as the response: [ { "LINKNAME": "Annual Training", "HITS": 1 }, { "LINKNAME": "In Focus Newsletter", "HITS": 1 }, { "LINKNAME": "NITA (secured)" ...

What separates name="" from :name=""?

If the :name="name" syntax is used, the value of the name attribute will be the unique data it receives from the props. However, if I use name="name" without the preceding :, then it will simply be "name". What role does the : play in the name attribute? ...

A Guide to Setting the HTML Lang Attribute on a Specific Page in Next.js

I have a website built with Next.js that consists of several pages. Most of the pages are in English, but there is one page that is in French and does not have an English version. How can I assign the lang attribute to the HTML tag for this specific page ...

I am looking to fetch information from a different Firestore collection by looping through data using a forEach method within an onSnapshot function

I'm struggling to grasp the concept of rendering data from Firestore in my project. I've searched extensively but haven't been able to find a solution that fits my requirements. Background Information In my Firestore database, I have collec ...

Unable to retrieve props from server-side page to client-side component in a Next.js application router

Currently, I am utilizing app router alongside Next.js version 13.5. Within my /dashboard page (which is a server component), there is an ApiKeyOptions client component embedded. However, when attempting to pass props from the dashboard page to the ApiKeyO ...

What is the best way to reference a const from a different class in React?

I'm relatively new to ReactJS, specifically using NextJS. In my project, I have two files - index.js and welcome.js In index.js, I've added Welcome as a component, along with a const called hideWelcome to hide the component and perform some acti ...

Retrieving and submitting text in a NodeJS environment

I'm attempting to retrieve text from an API that only provides a string of text ((here)), but I am encountering difficulties in displaying it accurately. When I try to post it, the output shows as [object Response], and the console.log is not showing ...

Enhancing Tables with Angular for Dynamic Translation and Filtering

I'm facing a challenge with my search feature in a basic table - <table> <thead> <tr> <th> Name </th> <th> Lastname </th> <th> Job Title </th> </tr> </the ...