Setting various colors for different plots within a single chart: A step-by-step guide

I'm currently tackling a project that requires me to showcase two different plots on the same chart, one being a "SPLINE" and the other a "COLUMN". My aim is to assign distinct background colors to each of these plots. Please note that I am referring to the background color rather than the color of the series itself.

https://i.stack.imgur.com/s7okA.png

Specifically, I am looking to have a unique color for the spline chart and another for the navigator and column chart.

I will include the necessary code below:

chartOptions = {
    chart: {
      styledMode: true,
      marginTop: 51,
      marginRight: 40,
      marginLeft: 20,
      backgroundColor: '#FCFFC5'
    },
    navigator: {
      top: 1,
      series: {
        type: 'spline'
      },
      adaptToUpdatedData: true,
      xAxis: {
        labels: {
          enabled: false,
        }
      }
    },
    rangeSelector: false,
    plotOptions: {
      series: {
        showInNavigator: true,
        gapSize: 0
      }
    },
    xAxis:{
      labels: {
        enabled: true,
      },
      tickColor: 'white',
      events: {
        afterSetExtremes: (e) => {
          var fromDate = e.min;
          var toDate = e.max;
          if(this.timeout){
            clearTimeout(this.timeout);
            this.timeout = 0;
          }
          this.timeout = setTimeout(
            () => {
              console.log("hello");
              this.restService.updateDates({fromDate: moment(fromDate).format("YYYY-MM-DD"), toDate: moment(toDate).format("YYYY-MM-DD")});
            }, 1000
          );
        }
      }
    },
    yAxis: [
      {
        type: 'logarithmic',
          min: 0.1,
          labels: {
            align: 'left',
            x: 5,
            formatter: function () {
              if (this.value === 0.1) {
                return 0;
              } else {
                return Highcharts.Axis.prototype.defaultLabelFormatter.call(this);
              }
            }
          },
        height: '100%',
        offset: 0,
        lineWidth: 2,
      },
      {
        type: 'logarithmic',
          min: 0.1,
          labels: {
            align: 'right',
            x: -5,
            formatter: function () {
              if (this.value === 0.1) {
                return 0;
              } else {
                return Highcharts.Axis.prototype.defaultLabelFormatter.call(this);
              }
            }
          },
        top: '110%',
        height: '30%',
        lineWidth: 2,
        offset:0,
        //labels : { x : 5, align: 'left' }
      },
      {
        opposite: true,
        height: '70%',
        offset: 0,
        lineWidth: 2,
        left:'-100%',
        labels : { x : -5, align: 'left' }
      },
      {
        opposite: true,
        top: '70%',
        height: '30%',
        lineWidth: 2,
        offset:0,
        left:'-100%',
        labels : { x : -5, align: 'left' }
      }
    ],
    series: [
  ],
  tooltip: {
                pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> Db',
                valueDecimals: 0,
                split: true
              },
  responsive: {
          rules: [{
              condition: {
                  maxWidth: 4500
              },
              chartOptions: {
                  chart: {
                      height: 400
                  },
                  subtitle: {
                      text: null
                  },
                  navigator: {
                      enabled: true
                  }
              }
          }]
      }
  };

Answer №1

One way to accomplish this is by utilizing the yAxis.plotBands for each yAxis. Keep in mind that the navigator also has a yAxis where plotBands can be implemented.

Code:

var stockData = [
  [1541514600000, 201.92, 204.72, 201.69, 203.77],
  [1541601000000, 205.97, 210.06, 204.13, 209.95],
  // Add more data here...
];

var volumeData = [
  [1541514600000, 31882900],
  [1541601000000, 33424400],
  // Add more data here...
];

Highcharts.stockChart('container', {
  chart: {
    events: {
      load: function() {
        var chart = this;

        chart.yAxis[0].addPlotBand({
          color: 'rgba(255, 0, 0, 0.2)',
          from: chart.yAxis[0].min,
          to: chart.yAxis[0].max
        });

        chart.yAxis[1].addPlotBand({
          color: 'rgba(0, 255, 0, 0.2)',
          from: chart.yAxis[1].min,
          to: chart.yAxis[1].max
        });
        
        chart.navigator.yAxis.addPlotBand({
          color: 'rgba(0, 0, 255, 0.1)',
          from: chart.yAxis[1].min,
          to: chart.yAxis[1].max
        });
      }
    }
  },
  navigator: {
  maskFill: 'rgba(0, 0, 0, 0.15)'
  },
  title: {
    text: 'Stock Data'
  },
  yAxis: [{
    labels: {
      align: 'right',
      x: -3
    },
    title: {
      text: 'OHLC'
    },
    height: '60%',
    lineWidth: 2,
    resize: {
      enabled: true
    }
  }, {
    labels: {
      align: 'right',
      x: -3
    },
    title: {
      text: 'Volume'
    },
    top: '65%',
    height: '35%',
    offset: 0,
    lineWidth: 2
  }],
  tooltip: {
    split: true
  },
  series: [{
    type: 'spline',
    name: 'Stock',
    data: stockData
  }, {
    type: 'column',
    name: 'Volume',
    data: volumeData,
    yAxis: 1
  }]
});
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/drag-panes.js"></script>
<div id="container"></div>

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

Embedding Globalize.js into an Angular component

Hey there! I'm currently working on building an Angular 4 application that needs to support L10n. I've decided to incorporate globalize into my project. Below is a snippet of my App component: import { Component, OnInit } from '@angular/c ...

The parent component can successfully call the setState function, but for some reason, the

In my code structure, I have the following setup (simplified): Here is the parent component: //code... const {handleClick} = useClick; <ul> {actions.map((action: string) => ( <li onClick={() => handleClick()} key={uuidv4()}> ...

Do I need to convert AngularJS to .ts for an Angular/AngularJS hybrid application?

Currently in the process of upgrading from AngularJS v1.25 to Angular 14 using the ng-Upgrade approach outlined on angular.io/guide/upgrade. Adding an extra challenge, our main page is built with ASP.NET MVC 5, and I am aiming to incorporate the Angular CL ...

Stop the interval once the route is altered in Angular 2

After initiating a timer within an Angular 2 component located inside a router outlet, I encounter a problem when switching routes. The timer continues to run even after leaving the route. How can I ensure that the timer is properly stopped upon route ch ...

Is it advisable to avoid circular imports in typescript development?

After spending 4 long hours troubleshooting a TypeScript error, I finally found the root cause. Object literal may only specify known properties, and 'details' does not exist in type 'Readonly<{ [x: `details.${string}.value`]: { value: st ...

Executing a Parent Function from a Child Component in Angular 11

I have successfully passed values between Angular components using Input/Output several times before, but I am currently facing a unique situation for which I cannot find a solution: There are two components involved: home.component (parent component) T ...

What is the best way to utilize a reduce function to eliminate the need for looping through an object in JavaScript?

Currently, my code looks like this: const weekdays = eachDay.map((day) => format(day, 'EEE')); let ret = { Su: '', Mo: '', Tu: '', We: '', Th: '', Fr: '', Sa: '' }; w ...

Navigating the complexities of integrating Rollup, ES modules, TypeScript, and JSX can be a challenging endeavor due to

Lately, I've been learning about the tools mentioned in the title. However, I've encountered some bumps along the way, so I'm turning to StackOverflow for help. My Requirements I need something like Rollup to pack my stuff For bare module ...

What are some secure methods for integrating iframes into an Angular 7 project?

Is there a secure method to set the URL for an iframe without bypassing security measures like using this.domsanitizer.bypassSecurityTrustResourceUrl(url)? While this approach may be flagged as a high vulnerability by tools such as Veracode, is there a w ...

Exploring the differences between Office Fabric UI's I[component]StyleProp and the I[component]Styles interface

The Office Fabric UI documentation provides two interfaces for each component, such as https://developer.microsoft.com/en-us/fabric#/components/nav includes INavStyleProps interface and INavStyles interface A component that implements INavStyleProps ...

Angular 2+ interactive popup with timer and automatic redirection

When making a request on mongodb, I need to display a modal window with an hourglass while the request is loading. The modal window should disappear once the request is finished, and if possible, redirect to another route. Technologies Used: Angular 2+, N ...

Transfer your focus to the following control by pressing the Enter key

I came across a project built on Angular 1.x that allows users to move focus to the next control by pressing the Enter key. 'use strict'; app.directive('setTabEnter', function () { var includeTags = ['INPUT', 'SELEC ...

The propagation of onClick events in elements that overlap

Having two divs absolutely positioned overlapping, each containing an onClick handler. The issue is that only the top element's onClick handler fires when clicked. React 17 is being used. Here is some sample code: <div style={{ position: "abs ...

Whenever a file is chosen, I aim to generate the video HTML dynamically and display the video with play functionalities using Angular 2 and TypeScript

I am attempting to allow users to select a video file and display it so they can play it after choosing the file. Below is my HTML code: <br> <input type="file" (change)="fileChangeEvent($event)" placeholder="upload file..." class=" ...

An issue has been detected in the @angular/material/autocomplete/typings/autocomplete-origin.d.ts file: The type 'ElementRef' is not declared as a generic type

Recently, I downloaded an Angular template that utilizes the Angular Material library. While trying to run this template on my local machine, I successfully executed the npm install command. However, when attempting to run ng serve, I encountered several w ...

Adding data to an array from a JSON source using Angular 5

When I receive a response from an endpoint, it looks like this: { "data": [{ "volume": 4.889999866485596, "name": "Carton03", "weight": 5.75, "storage": 3 }, { "volume": 2.6500000953674316, "name": "Carton02", "weight": 4.5 ...

ReactForms Deprication for NgModel

According to Angular, certain directives and features are considered deprecated and could potentially be removed in upcoming versions. In a hypothetical scenario, let's say I am using NgModel with reactive forms, which Angular has marked as deprecate ...

Tips for mocking Dependent Modules in Jasmine when dealing with a plethora of dependencies in Angular 9

Looking to create a unit test for a component within an Angular project. The main component has 5-6 dependencies and extends another class with around 7 additional dependencies. What is the most effective method to set up the TestBed for this component? ...

Retaining previous values in Angular reactive form during the (change) event callback

Imagine having an Angular reactive form with an input field. The goal is to keep track of the old value whenever the input changes and display it somewhere on the page. Below is a code snippet that achieves this functionality: @Component({ selector: & ...

Sending reference variable from Angular input type=file

I am currently learning Angular and I have implemented a feature where a list of PDF files is displayed using an array called pdfs. In my template, these PDF files are parsed into "card" elements for better visualization. The issue arises when I attempt ...