Tips for concealing the bar graph while maintaining the visibility of the data labels in HighCharts

Is there a way to hide one bar but keep the data labels in HighCharts? I have 3 bars:

  1. Target
  2. Realization
  3. Percentage


I want to display only the first and second bars, with only 1 data label which is the percentage. So, I made some adjustments to my code:
Here is a sample:

var target = [50,100];
var realization = [10,40];
var percentage = [];

for(i = 0; i < target.length; i++) {
  var divide = (realization[i] / target[i]) * 100;
  if (divide == Number.POSITIVE_INFINITY || divide == Number.NEGATIVE_INFINITY || isNaN(divide)) {
    percentage.push(0);
  } else {
    percentage.push(divide);
  }
}
series: [
    {
      name: 'Target )',
      color: '#009933',
      data: target,

    },
    // I used a trick on the second series to achieve the desired display
    {
      name: 'Percentage',
      data: percentage,
      color: 'rgba(255, 255, 255, .4)',
      showInLegend: false,
      pointWidth: 1, 
      lineColor: 'transparent',
      marker: { 
        fillColor: 'transparent',
        states: {
          hover: {
              enabled: false
          }
        }    
      }
    },
    {
      name: 'Realization',
      color: '#00ff00',
      data: percentage,
    }]

It will look like this https://i.sstatic.net/DL0C8.png The trick I used is to place the percentage in the middle and change the bar color to transparent.
Here is the expected result https://i.sstatic.net/QkTpw.png
This is my full code :
https://jsfiddle.net/xanrdswq/
This is just a temporary solution for now.

Answer №1

One way to easily accomplish this is by using the Highchart.SVGRenderer.text method, which allows you to draw custom text. You can add labels in the render event callback or chart callback, especially when the chart width is fixed.

Feel free to check out the code and demo provided below and reach out if you have any questions or need further clarification.

Code:

chart: {
  type: 'bar',
  events: {
    render: function() {
      const chart = this,
        xAxis = chart.xAxis[0],
        yAxis = chart.yAxis[0],
        offsetX = 5;

      let customElems = chart.customElems || [],
        y,
        x,
        element;

      if (customElems.length) {
        customElems.forEach(elem => {
          elem.destroy();
        });

        customElems.length = 0;
      }

      chart.series[0].points.forEach((point, i) => {
        x = yAxis.toPixels(point.y) + offsetX;
        y = xAxis.toPixels(point.x);

        element = chart.renderer.text(`${percentage[i]} %`, x, y).css({
          fill: '#000'
        }).add().toFront();

        customElems.push(element);
      });

      chart.customElems = customElems;
    }
  }
}

Demo:

API reference:

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

A dynamically-generated dropdown element in the DOM is being duplicated due to JavaScript manipulation

Currently, I am dynamically adding a dropdown element to the page using javascript. The goal is for this dropdown to modify the properties displayed on a map. However, when attempting to add the element after the map loads, I encounter an issue where the d ...

Sending an image dynamically as a prop to a child component

Within my parent component, I retrieve an object from an API which I later enhance with an image as a key/value pair. Subsequently, I pass this modified object to a child component for rendering. In order to accomplish this, I referred to the following pos ...

What is the most effective method for utilizing JSON as a database?

For my upcoming offline mobile web app project, I am considering using JSON to mirror some of my database tables and storing the data in localStorage. (Although Web SQL Database is an option, its future-proofing capabilities are questionable.) Initially, ...

Leverage the power of JSON values by incorporating them directly into HTML tags

My JSON file is generating the following styles: { "h1" : { "font-family" : "Lato", "font-size" : "24px", "line-height" : "28px", "font-weight" : 600, "colorId" : 3, "margin-bottom" : "10px", "margin-top" : "20px" }, "h2" : { ...

Is it possible to attach a mouse click event to styled text?

Is there a way to specify a mouse click event for an element with a decoration applied to the text, matched with regex? The option to specify a hoverMessage is available, but I would like to find a way to execute a function based on which decorated text ...

Tips for dynamically loading images as needed

I'm working on a simple image zoom jQuery feature using elevateZoom. You can see a Demo example here. The implementation involves the following code: <img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/> <sc ...

Obtain numerous JSON pages using jq

When making an API call, I receive a JSON response that can be formatted nicely using curl "https://mywebsite.com/api/cars.json&page=1" | jq '.' Displayed below is a sample of the output. Since there are multiple pages of data (112 total ...

Removing an object from an array if it does not exist in another array: A step-by-step

Looking to remove an object from an array if it's not present in another array. After doing some research, I came across a similar question on this link, but with a different array source. Below is the example from the link: var check = [1, 2, 3]; ...

Ensuring React Native/Redux child components receive the latest state updates with every change

When using <NavigationCardStack/> as the root component in React Native and Redux to render routes with _renderScene(), I noticed that the updated state is not always passed down every time there is a state change. Despite having console.log(this.pro ...

Ways to extract information from a dynamically loaded webpage

Is there a way to extract data from a news website that automatically reloads at set time intervals? I want to use this data on my own website as information, whether it's in the form of images or text. Can anyone guide me on how to retrieve data from ...

"Exploring the Power of TypeScript Types with the .bind Method

Delving into the world of generics, I've crafted a generic event class that looks something like this: export interface Listener < T > { (event: T): any; } export class EventTyped < T > { //Array of listeners private listeners: Lis ...

Static addition of the Button to the parent div is crucial for seamless

Introduction: My current project involves managing interns, and I am focusing on the employee side. Employees have the ability to add, edit, and delete interns through modal popups. Strategy: To avoid unnecessary repetition of code, I decided to create a ...

Deleting multiple subdocuments and their related subdocuments with Mongoose

In my application, I have a Project document that contains an array of subdocuments structured as Tasks. Each Task has its own array of subdocuments with a schema called Comments. const projectSchema = new Schema({ _id: Schema.Types.ObjectId, name: { ...

What is the best way to use JavaScript to emphasize a substring that includes a wild card character surrounded by two specific characters

In the dataframe below, I have multiple strings stored: v1 v2 ARSTNFGATTATNMGATGHTGNKGTEEFR SEQUENCE1 BRCTNIGATGATNLGATGHTGNQGTEEFR SEQUENCE2 ARSTNFGATTATNMGATGHTGNKGTEEFR SEQUENCE3 I am interested in searching for a ...

difficulty in detecting cordova deviceready

When developing my iOS app using JavaScript, I included cordova.js in my index.html file. The deviceready function is called correctly upon first login, but when I logout and then login again, the device ready event does not trigger. document.addEventLi ...

Issue with retrieving data using AngularJS Restangular

I've been trying to figure out how to make restangular work properly. When I call my API (using the endpoint /user) I receive the following JSON response: { "error": false, "response": { "totalcount": 2, "records": [{ "id": "1", ...

Creating unique border-radius for each point in a Highcharts column chart with React

Let's flip the script and start at the finish line. My goal is to customize my column chart to resemble this design: https://i.stack.imgur.com/FckJB.png Creating this style is a breeze with chart.js Credit: I've already delved into this inquiry ...

Transforming an object into an array of objects with the power of JavaScript

Looking to transform an object with the following structure: { From: {"A","B","C"}, To: {"A1","B1","C1"}, value: {1,2,3} } I need to convert this array: [ {from: "A" ,to: "A1" , value: 1 }, {from: "B" ,to: "B1" , value: 2}, {from: "C" ,to: "C1" ...

The functionality of string replacement is ineffective in the Safari browser

When using the code "MM/DD/YYYY".replace(/.?YYYY.?/, ''); , Chrome displays MM/DD, while Safari shows an empty string. Why does this difference occur? Is there a method that will produce consistent results across all browsers? ...

Using dynamic tag names within React JSX can greatly enhance the flexibility and

I'm working on creating a React component for HTML heading tags (h1, h2, h3, etc.), where the heading level is determined by a prop. Here is how I attempted to approach it: <h{this.props.level}>Hello</h{this.props.level}> My expected out ...