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

Expanding User Type to Include Extra User Data Using NextAuth.js

I encountered a dilemma where I needed to include the "profile" property in my section object to cater to different user personas in my application. However, despite retrieving the logged-in user's data from the backend and storing it in the NextAuth. ...

Angular: Exploring the possibilities of condition-based click event implementation

In my component, there are two elements: 'order information' and a 'datepicker'. When clicking on the component, it will display the order information. However, I want to prevent the click event from being triggered if the user clicks ...

RXJS - Implementing a conditional logic in the switchMap operator to determine if it's the first

In my service's http fetch method, there is a parameter called "showLoadingSpinner". When this parameter is set to false, the HttpContext DISABLE_LOADER_FOR_REQUEST = true will be set. I would like to set showLoadingSpinner to false for every subsequ ...

Setting up Electron with React and TypeScript: A Comprehensive Guide

I've been developing an app using Electron, React (jsx), and Babel. However, I recently made the switch to TypeScript and I'm struggling to get everything functioning properly. The npm packages I've tried only work for either React or TypeSc ...

The error message ``TypeError [ERR_UNKNOWN_FILE_EXTENSION]:`` indicates a

I am encountering an error while trying to run the command ./bitgo-express --port 3080 --env test --bind localhost: (node:367854) ExperimentalWarning: The ESM module loader is experimental. internal/process/esm_loader.js:90 internalBinding('errors ...

Utilizing Angular 8 (TypeScript) and .NET Core to send a GET request with dates as a parameter

I attempted to send 2 dates as parameters in the GET request, but I am only receiving this: Model public class Dates { public DateTime from { get; set; } public DateTime to { get; set; } } .net core [HttpGet] [Route("main/exportToEx ...

What is the best way to eliminate the Mat-form-field-wrapper element from a Mat-form-field component

I have implemented Angular mat-form-field and styled it to appear like a mat-chip. Now, I am looking to remove the outer box (mat-form-field-wrapper). <div class="flex"> <div class="etc"> <mat-chip-list i18n-aria-lab ...

Issue with alignment of Ionic 4 toolbar

Has anyone encountered an issue with the toolbar alignment in angular 8/ionic 4? Below is the code snippet for the footer of tab2.page.html: <ion-footer> <ion-toolbar> <ion-buttons start> <button ion-button icon-only colo ...

What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation. In the Angular 11 demo, scrolling functions perfectly an ...

Understanding a compound data type in TypeScript

Hey there, I'm new to TypeScript and I'm facing a challenge in defining the type for an object that might have the following structure at runtime: { "animals" : [ { name: "kittie", color: "blue" }, { name: ...

What is the best method for sorting through observable data pulled from an API?

public data$: Observable<any[]>; ngOnInit(): void { this.data$ = this.InventoryService.getAllProducts(); } searchProducts(event: any) { let searchTerm: string = event.target.value; console.log(searchTerm); this.data$.pipe( ...

In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with: export class UserListComponent implements OnInit, OnDestroy { private _subscriptions: Subscription; private _users: User[] = []; private _clickableUser: boolean = true; constructor( priv ...

Enable the generation of scss.d.ts files with Next.js

I'm currently working on a project that requires the generation of .d.ts files for the scss it produces. Instead of manually creating these files, I have integrated css-modules-typescript-loader with Storybook to automate this process. However, I am ...

What is the correct way to construct an object in TypeScript while still taking types into account?

Hey, I'm having trouble implementing a common JavaScript pattern in TypeScript without resorting to using any to ignore the types. My goal is to write a function that constructs an object based on certain conditions and returns the correct type. Here& ...

Beware of the 'grid zero width' alert that may appear when utilizing ag-Grid's sizeColumnsToFit() function on multiple ag-Grids that are shown within a tab menu

Encountering a warning message when resizing ag-Grid and switching between tabs. The warning reads: ag-Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen? A demo of this ...

Extract information from the website "angular.callbacks" using web crawling techniques

Looking to utilize R for scraping news from the following URL: "AlphaGo"&ss=fn&start=0). Below is the code I am working with: url <- "http://api.foxnews.com/v1/content/search?q=%22AlphaGo%22&fields=date,description,title,url,image,type,taxo ...

Incorporate typings into your CDN integration

I'm interested in utilizing a CDN to access a JSON validation library, as it's expected to provide faster performance (due to retrieving the file from the nearest server within the CDN). The JSON validation library in question can be found here: ...

What is the best way to retrieve information from a sibling state?

The current structure I'm working with includes: --Users --User Table Component --User Filtering State Upon navigating to the Users section, I encounter the User Table Component. My goal is to retrieve an object located within this component usi ...

Having trouble getting the React form validation to work using Material UI TextField and TypeScript

I'm having trouble implementing validation on a "sign up" page using the MUI library in React with TypeScript. I've added the "required" attribute to each TextField tag, but the validation doesn't seem to be working upon submission. I'v ...

How to Connect Select Dropdown to a Static Array Object in Angular 2

I have connected my Select DropDown to static data. FieldModel.ts export interface Field { id : number; title : string; } app.PeopleListService.ts import { Injectable } from '@angular/core'; import { Field } from "../model/fieldMo ...