Is it possible to split the legend for a Highstock double yAxis?

Is it possible to have a distinct legend for each yAxis when they are split in highstock? I am using a stacked bar chart with the same data series running on both yAxes, resulting in duplicated entries in the legend at the top. Can the legend be divided into two sections, with the second one placed lower down above the second yAxis?

If anyone can provide guidance on the configuration below, I would greatly appreciate it. I have included a screenshot so you can see how it currently appears. I would like the second green 'direct consumption' + 'Charge' + 'export' on the lower legend.

https://i.sstatic.net/0M3UL.png

// Highstock split stacked column chart
    Highstock.setOptions({
      colors: ['#FB654B', '#FFBE6B', '#2FC099', '#2FC099', '#FF8954', '#FCEA6E']
    });

    Highstock.stockChart('container2', {
      chart: {
        type: 'column'
      },
      title: {
        text: 'Energy Balance History'
      },
      xAxis: {
      type: 'datetime'
      },
      legend: {
        layout: 'horizontal',
        align: 'center',
        verticalAlign: 'top',
        enabled: true,
        x: 0,
        y: 50
      },
      navigator: {
        height: 30,
        series: {
            data: <%- JSON.stringify(solarValuesDays)  %>
        }
      },
      rangeSelector: {
        buttons: [{
          type: 'week',
          count: 1,
          text: '1w'
        }, {
          type: 'week',
          count: 2,
          text: '2w'
        }, {
          type: 'month',
          count: 1,
          text: '1m'
        }, {
          type: 'all',
          text: 'All'
        }],
        inputEnabled: true, // it supports only days
        selected: 1 // month
      },
      yAxis: [{
        labels: {
          align: 'right',
          x: -3
        },
        min: 0,
        title: {
          text: 'Consumption Energy (kWh)'
        },
        height: '50%',
        lineWidth: 2,
        stackLabels: {
          enabled: true,
          formatter: function () {
            return Highcharts.numberFormat(this.total,2);
          },
          style: {
            fontWeight: 'bold',
            color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
          }
        }
      },{
      labels: {
        align: 'right',
        x: -3
      },    
      min: 0,
      title: {
        text: 'Generation Energy (kWh)'
      },
      top: '53%',
      height: '50%',
      linkedTo: 0,
      lineWidth: 2,
      offset: 0,
      stackLabels: {
        enabled: true,
        formatter: function () {
          return Highcharts.numberFormat(this.total,2);
        },
        style: {
          fontWeight: 'bold',
          color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
        }
      }
      }],
      tooltip: {
        pointFormat: '{series.name}: {point.y:.2f}'
      },
      plotOptions: {
        column: {
          stacking: 'normal'
        }
      },
      series: [{
      name: 'Import',
      yAxis: 0,
      data: <%= JSON.stringify(importValuesDays) %>
      }, {
      name: 'Discharge',
      yAxis: 0,
      data: <%=JSON.stringify(dischargeValuesDays)  %>,
      }, {
      name: 'Direct Consumption',
      yAxis: 0,
      data: <%= JSON.stringify(dirConsumptionValuesDays)  %>
      }, {
      name: 'Direct Consumption',
      yAxis: 1,
      data: <%= JSON.stringify(dirConsumptionValuesDays)  %>
      }, {
      name: 'Charge',
      yAxis: 1,
      data: <%=JSON.stringify(chargeValuesDays)  %>
      }, {
      name: 'Export',
      yAxis: 1,
      data: <%= JSON.stringify(exportValuesDays) %>
      }]
    });

Answer №1

By default, the legend cannot be split, but with some custom code, you can reposition legend items:

let H = Highcharts;

H.wrap(H.Legend.prototype, 'positionItems', function(proceed) {
    proceed.apply(this, Array.prototype.slice.call(arguments, 1));

    let items = this.allItems;

    items.forEach(function(item, i) {

        if (i > 1) {
            item.legendGroup.attr({
                translateY: 215,
                translateX: item.legendGroup.translateX - this.legendWidth / 4
            });
        } else {
            item.legendGroup.attr({
                translateX: item.legendGroup.translateX + this.legendWidth / 4
            });
        }
    }, this);
});

Check out the live demo here.

For more information, refer to the Highcharts documentation here.

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

Axios: Exception handling does not involve entering the catch method

Implementing a function to adjust a contract name involves making an axios request to the backend API using a specific ID. Upon each execution, a sweetalert prompt is displayed. axios({ url: '/api/contract/' + id, method: 'put ...

Is the JQuery Mobile .page() method triggering an endless loop?

Creating a dynamic listview with data from an AJAX response has been successful, however, when using JQM's .page() function on it, it appears to enter an infinite loop where the listview keeps getting appended indefinitely. I'm unsure if this is ...

What is the process of sending a component as props using props in react?

Currently, I am utilizing the react-grid library provided by dev-express. Within this library, there is a Table component that allows us to pass in a Cell component. In my CustomCell component, I have integrated the Menu component from Material UI. < ...

Why is $scope.$watch('$destroy') being called in Angular UI Router 1.0 even when not leaving the state?

Take a look at the plunker here. My understanding is that $scope.$watch('$destroy') should be invoked when $scope is on the verge of being destroyed. In the provided example, it seems that upon entering a state, the $scope.$watch('$destroy ...

What is the best way to sort and organize this JSON data?

There is an array of JSON objects named events that contains fields such as eventId, eventName, and the date of the event. [{event1}, {event2}, {event3}]; The goal is to iterate through this array and filter out events that occur on the same day. The des ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

executing functions that return a JSX component within the render method

In an effort to enhance readability, I am striving to condense the length of the render() method by utilizing class methods that contain isolated JSX elements. A snag arises when attempting to apply this technique to more than one JSX element. Despite en ...

What is the best way to modify the ID of a duplicated element?

I have been working on creating a drag and drop editor using react-smooth-dnd. The setup involves two containers: a toolbar with elements and an editor where the elements can be dragged and dropped. Each element in the toolbar has the following structure: ...

Achieving the retrieval of all data can be done simply by utilizing the `echo json_encode($data);

I am trying to automatically update the user wall with new data from the database using a script that checks for updates every 15 seconds. Everything works fine when I only use one piece of data like $data = $row['description']; in the server.ph ...

Reload a jquery pop up upon closing a pop up window

I have a modal pop up that appears after clicking an ASP button : <div class="form-group"> <asp:Button ID="btnBrand" runat="server" Text="Add brand" CssClass="btn btn-info" OnClick="btnAdd_Click" /> </div> Code Behind : protected ...

Can a small white pop-up be triggered by clicking a button?

While exploring the website , I noticed that clicking on Availability Zones opens a small window with text on the right side of the page. Is it possible to achieve a similar feature on a leaflet map without using JavaScript? This functionality would be tri ...

Encountering errors while attempting to render MUI components in jsdom using react testing library within a mocha test

Due to the lack of maintenance and support for React 18+ in enzyme, I am faced with the task of migrating over 1750 unit tests to work with react-testing-library and global-jsdom. This migration is necessary so that our application can continue running on ...

How can I ensure that the size of the Dropdown Menu Item matches its parent in both Bootstrap and CSS styles?

I am working on a navigation bar that has a dropdown menu which appears on hover. I want the size of the dropdown menu items to match the size of the parent element. Here is an image for reference: https://i.stack.imgur.com/oNGmZ.png Currently, the "One ...

Error with Ant Design Autocomplete functionality when searching for a number

I am currently using ant design to develop a more advanced autocomplete component that will display data from multiple columns. In this particular scenario, I have two columns named tax_id and legal_name that users can search by. Everything works smoothly ...

Issue with directive not activating when attribute is changed

I am facing an issue with my website where users can make selections from two dropdowns, and based on those values, attributes are sent to directives for a corresponding function to be called. The problem I'm encountering is that the directives are n ...

The utilization of useState can potentially trigger an endless loop

Currently, I am in the process of developing a web application using Next.js and Tailwind CSS. My goal is to pass a set of data between methods by utilizing useState. However, I have encountered an issue where the application loads indefinitely with excess ...

AngularFire and Ionic - There is no data being sent to the server from the form

I am using Ionic and AngularFire to build my app, but I have encountered a new issue: the form data is empty! Only the fields in my Firebase database are visible. How can I retrieve the user-entered form data from the Firebase database? Here is a screensh ...

Modify the content of a tooltip when hovering over the session times button

My website coded in ASP.Net is able to generate buttons which contain the following HTML code: <a id="1173766" val="248506" titletext="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening& ...

Tips for resizing the background to match the font size on a canvas marker in Google Maps

Check out my jsFiddle code below: var marker = new google.maps.Marker({ position: new google.maps.LatLng(-25.363882,131.044922), map: map, title:"Hello World!", icon: CanvasCrear("hola", 15) ...

Update the content of a div element with the data retrieved through an Ajax response

I am attempting to update the inner HTML of a div after a certain interval. I am receiving the correct response using Ajax, but I am struggling to replace the inner HTML of the selected element with the Ajax response. What could be wrong with my code? HTM ...