Learn how to customize the background colors of the x and y axes in Highcharts graphs

I am attempting to modify the background color of the highcharts x and y axis.

My goal is to apply a fill color as shown in the highlighted image below.

https://i.sstatic.net/NX6nF.jpg

Answer №1

Unfortunately, axes objects do not support the backgroundColor attribute. However, you can use a workaround by creating a rectangle behind both axes using Highcharts SVGRenderer, as shown in the following example.

Sample code:

  chart: {
    spacingLeft: 0,
    events: {
      render: function() {
        const chart = this,
          xAxisBox = (chart.xAxis[0].gridGroup.getBBox()),
          yAxisBox = (chart.yAxis[0].gridGroup.getBBox());

        if (!chart.customXaxisBackground) {
          chart.customXaxisBackground = chart.renderer.rect()
            .attr({
              'stroke-width': 0,
              stroke: 'orange',
              fill: '#C7DCD8',
              zIndex: 0
            })
            .add();
        }

        chart.customXaxisBackground.attr({
          x: xAxisBox.x,
          y: xAxisBox.y - chart.plotTop / 2,
          width: chart.plotWidth,
          height: chart.plotTop / 2
        })

        if (!chart.customYaxisBackground) {
          chart.customYaxisBackground = chart.renderer.rect()
            .attr({
              'stroke-width': 0,
              stroke: 'orange',
              fill: '#C7DCD8',
              zIndex: 0
            })
            .add();
        }
        chart.customYaxisBackground.attr({
          x: yAxisBox.x - chart.plotLeft,
          y: yAxisBox.y,
          width: chart.plotLeft,
          height: chart.plotHeight
        })
      }

    }
  },

Live demonstration: https://jsfiddle.net/BlackLabel/165720Lm/

References for further information: https://api.highcharts.com/highcharts/chart.events.render https://api.highcharts.com/class-reference/Highcharts.SVGRenderer

Answer №2

Setting a background color for the axis in Highcharts may not have a direct attribute, but you can achieve this by creating a custom style using SVGRenderer. This allows you to create a rectangle behind the axis and fill it with your desired color. Alternatively, if you only want to set the background for the axis labels, you can use the formatter function to display an HTML element as the label with a background color.

If you need guidance, here's an example that could assist you:

labels: {
    // Adding a background to xAxis labels using HTML
    formatter() {
        return `<span style="
                            background-color: orange; 
                            display: inline-block; 
                            width: 40px; 
                            text-align: center;
                           ">
                     ${this.value}
                 </span>`
    },
    useHTML: true
}
Highcharts.chart('container', {
    chart: {
        spacingLeft: 0,
        events: {
            render: function() {
                const chart = this,
                xAxisBox = (chart.axes[0].gridGroup.getBBox());
                chart.renderer.rect(xAxisBox.y/*position on X-axis*/ , chart.plotHeight + xAxisBox.y /*position on Y-axis*/ , chart.plotWidth /*width*/ , 25 /*height*/)
                .attr({
                    'stroke-width': 0,
                    stroke: 'orange',
                    fill: 'orange',
                    zIndex: 3
                })
                .add();
            }
        }
    },
    series: [{
        data: [2, 5, 2, 3, 6, 5]
    }]
});

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

HTTP Interceptor never finishes executing (finalization is never triggered)

In my angular 8 project, I created a basic HttpInterceptor that simply duplicates the original request and includes an additional parameter: @Injectable() export class RequestHeadersInterceptor implements HttpInterceptor { intercept(request: HttpReques ...

When using the Angular Material table with selection enabled, the master toggle functionality should always deselect the

I made modifications to the original Angular Material Table example - Stackblitz. In my version, when some rows are selected and the master toggle is clicked, all selected rows should be deselected (similar to Gmail behavior). The functionality works, but ...

Steps to eliminate the selection indicator(dot) from ng-bootstrap radio buttons

Check out this example from ng bootstrap: https://i.sstatic.net/YYEIW.png I copied the code into my Angular project with only minor changes to the label and value, but got a different result: https://i.sstatic.net/lfShy.png Here is the HTML markup that w ...

A Guide to Linking Checked Boxes to Form Arrays with FormBuilder in Angular

Currently, I am dealing with a collection of checkboxes and utilizing Angular's FormBuilder to handle my form. My objective is to link the values of the selected checkboxes to a form control named itemIds within my form group. constructor(privat ...

Utilizing shared components across a Next.js application within a monorepo

Utilizing a monorepo to share types, DTOs, and other isomorphic app components from backend services (Nest.js) within the same mono repo has presented some challenges for me. In my setup, both the next.js app and nest.js app (which itself is a nest.js mono ...

Using the `disableSince` option in `mydatepicker` for validating date of birth

Currently, I am utilizing the mydatepicker plugin for my calendar field, specifically for the Date of Birth field. It is important for me to disable future dates by setting the current date as a reference point. While exploring the documentation, I came ...

TypeScript mistakenly infers the incorrect type for AbstractControl when used with a generic type_declaration

My InnerComponent requires a FormArray as input, and in order to access the type of the controls within the array, I have introduced a type parameter called ControlValue. The input is declared to be of type FormArray<AbstractControl<ControlValue>& ...

Is there a way to simulate the BeforeInstallPromptEvent for testing in Jasmine/Angular?

I'm currently working on testing a dialog component that manages the PWA install event triggered manually when a specific function is invoked. The goal is to handle the promise returned by the BeforeInstallPromptEvent.userChoice property. However, wh ...

Leveraging Razor for creating Angular2 templates

I'm attempting to utilize Razor to create the html used in an Angular template. My setup involves Angular v 2.0.0 and this is how my Contract.cshtml file looks: <script> System.import('contract.js').catch(function(err){ console.err ...

React TypeScript throws an error when a Socket.IO object is passed to a child component and appears as undefined

Currently, I'm developing a simple chat application as part of my university course. The code below represents a work-in-progress page for this project. While I am able to get the socket from the server and use it in the main component without any is ...

How to access the state of an @ngrx/data entity in a reducer function in ngrx 8

I am trying to access the state of a ngrx/data entity within a reducer function. Currently, I am working on implementing a pager (pagination) feature where users can navigate through different pages. However, I am facing a challenge in determining the tot ...

Gaining entry to a static member of an exported class in a module

I am facing an issue with my Typescript code snippet. The code is as follows: module MyModule { export class MyClass { static MyStaticMember : string; } } My requirement is to access this code from a separate file after compilation. I tri ...

What is the process for integrating Mocha into a create-react-app project that uses Typescript?

I have been working on a react application using create-react-app (typescript) and found that I prefer using mocha + enzyme for testing my React components instead of jest. In the past, I used the following test script: "test" :"NODE_ENV=development m ...

Access Denied: Origin not allowed

Server Error: Access to XMLHttpRequest at '' from origin 'http://localhost:4200' has been blocked by CORS policy. The 'Access-Control-Allow-Origin' header is missing on the requested resource. import { Injectable } from &apo ...

Unable to subscribe due to the return value being an AnonymousSubject rather than an Observable

I am facing an issue in Angular 4 where I am attempting to retrieve details from a specific user when clicking on the 'user link profile'. However, I am unable to subscribe to my function because the return value of switchMap is AnonymousSubject ...

Experimenting with retrieving input from other components while implementing setTimeout

In continuation of the previous question (linked here), I am still working on tutorials for Angular testing using the same files. The current issue revolves around the setTimeout function. Within both ngOnInit and ngAfterViewInit, I have included a setTim ...

"The limitation of character input in an Ionic Angular input field is not being

After installing the APK on my Android device, I noticed that the input field allows me to enter more than 5 characters even though I have set a maximum length in both the HTML and TypeScript files. This is how my HTML looks: <ion-row id="rowValid ...

The issue with loading scripts in a ReactJS NextJS app is related to the inline condition not working

I'm having trouble with an inline condition for loading scripts. The condition seems to be working because the tag is displaying text, but when it comes to scripts, it doesn't work. How can I resolve this issue? const cookie = new Cookies().get ...

Retrieve the final variable in an Observable sequence

In my code, I have a variable called 'messages' which stores messages from a conversation: messages: Observable<Message[]>; To populate the 'messages' variable, I do the following: const newMessage = new Message(objMessage); ne ...

What is the process for configuring NextJS to recognize and handle multiple dynamic routes?

Utilizing NextJS for dynamic page creation, I have a file called [video].tsx This file generates dynamic pages with the following code: const Video = (props) => { const router = useRouter() const { video } = router.query const videoData = GeneralVi ...