Customizing the color scheme for a bar chart using ng2-chart

https://i.sstatic.net/M4FWH.pngI am currently attempting to set colors for bars in a bar graph based on the range of values they represent.

TS

  public barChartData: any[];
  public chartColors: any[];
    value = [] // The array contains values retrieved from the database, such as [3.5, 2.5, 1.5, 6.5, 6, 1, 6.5, 3.5, 5.5]

    this.barChartData = [{
        data: this.value,
        label: 'Insulin'
    }]

    var l = this.value.length;
    for (var i = 0; i < l; i++) {
        if (this.value[i] <= 3) {
            this.chartColors = [{
                backgroundColor: 'rgba(255, 205, 86, 9)',
                borderColor: 'rgba(255, 205, 86, 9)'
            }]
        } else if (this.value[i] > 3 && this.value[i] <= 6) {


            this.chartColors = [{
                backgroundColor: 'rgba(255, 99, 132, 62)',
                borderColor: 'rgba(255, 99, 132, 62)'
            }];

        } else if (this.value[i] > 6) {

            this.chartColors = [{
                backgroundColor: 'rgba(54, 162, 235, -12)',
                borderColor: 'rgba(54, 162, 235, -12)'

            }];

        }

    }

This approach is not yielding the desired results. Can anyone provide guidance on the correct method to achieve this?

Answer №1

Your Code Issue :

if (this.value <= 3) {
this.chartColors = [{
    backgroundColor: 'rgba(255, 99, 132, 62)'
}]
} 

While implementing the if condition above, you unintentionally altered the entire 'this.chartColors' property instead of just changing the background color for inputs that meet the specified condition. See the correct way to define chart colors below.

public chartColors: Array<any> = [
{
  backgroundColor: ['rgba(63, 191, 127,  0.4)','rgba(191, 191, 63, 0.4)'],
   borderColor: ['rgba(63, 191, 127, 0.8)', 'rgba(63, 191, 191, 0.8)',
  hoverBackgroundColor: ['rgba(63, 191, 127, 0.6)', 'rgba(63, 191, 191, 0.6)',
  borderWidth: 2
}];

The properties like backgroundColor, borderColor, or hoverBackgroundColor contain arrays of colors corresponding to indexes in barChartData.data.

Here's the correct format for defining barChartData:

 public barChartData: any[] = [{
  data: [],
  label: ''
}];

Your data will be placed in barChartData.data = [Your required data goes here]

In Conclusion:

this.barchartData[0].data[index] corresponds to this.chartColors[0].backgroundColor[index] as the bar color.

Solution:

To resolve your issue, follow the code snippet below:

for (let index = 0; index < this.barChartData[0].data.length; index++) {
  if (this.barChartData[0].data[index] > 0 && this.barChartData[0].data[index] < 3 ) {
    console.log('>0' , this.barChartData[0].data[index]);
    this.chartColors[0].backgroundColor[index] = 'rgba(63, 191, 127,  0.4)';
  }
  // More conditions can be added similarly
}

This is a sample code. Adjust the values as needed according to your data. Feel free to reach out if you need further clarification.

Replace the following segment with your code :

// Your existing code snippet

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

Unable to define the type for the style root in Typescript

I am encountering an error that is asking me to code the following types in the root tag: No overload matches this call. Overload 1 of 2, '(style: Styles<Theme, {}, "root">, options?: Pick<WithStylesOptions<Theme>, "fli ...

Buttons for camera actions are superimposed on top of the preview of the capacitor camera

I am currently using the Capacitor CameraPreview Library to access the camera functions of the device. However, I have encountered a strange issue where the camera buttons overlap with the preview when exporting to an android device. This issue seems to on ...

Tips for utilizing the @Input() property of a component to set the initial value of an input field

Is there a way to utilize the value of an @Input() property on Component B as the initial value for an input field in that component when it is contained within Component A? I attempted passing the value during form construction, but found that it only wo ...

Tips for restricting a type field to a power of two within a type system

When looking at certain JavaScript code snippets, one may come across the following: function allocate(bits) { if ((bits & (bits - 1)) != 0) { throw "Parameter is not a power of 2"; } ... } In essence, there exists a restriction on ...

Is there a way for me to use TypeScript to infer the type of the value returned by Map.get()?

type FuncType<O extends Object> = (option: O) => boolean export const funcMap: Map<string, Function> = new Map() const func1: FuncType<Object> = () => true const func2: FuncType<{prop: number}> = ({ prop }) => prop !== 0 ...

Guide to assigning positions in an array of a particular component with its selector utilizing Angular:

I am a beginner when it comes to Angular and I have a question regarding setting positions of an array that is initially declared as empty in one component, using its selector in another component. Let's take for example a component named "array" whe ...

The CORS policy is refusing access to XMLHttpRequest from 'http://localhost:4200' to 'http://localhost:8082/kanchiwork/'

While attempting to transfer values from one server to another, I encountered an error stating "Access to XMLHttpRequest at 'http://localhost:8082/kanchiwork/' from origin 'http://localhost:4200' has been blocked by CORS policy". My .ts ...

How can the parent parameter be accessed from the @Input parameter in a child class within Angular 2?

In the parent component class, I have the following code: import {Component, OnInit, Input} from '@angular/core'; @Component({ }) export abstract class AbstractBlock{ //Input data @Input() config: any; getConfig() { return this. ...

Having trouble with typecasting in Angular 9 after receiving an HTTP response?

When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1: ngOnInit(): void { if(!this.student) { this.studentsService.getStudentDetail(this.id).subscribe( (response: Stu ...

What is the best way to make a class available in the global namespace within a TypeScript module?

The Issue at Hand Given an existing application with a mixture of modules and global scripts, the goal is to convert one class in a global script (gamma.ts) into a module. This entails adding `export default` before `class gamma {}` in gamma.ts. Additiona ...

The NG Bootstrap table is not displaying any data from Angular service once it has been called

I have been using the Angular Bootstrap library for my application development. Specifically, I utilized the Angular Bootstrap Table to create a page that displays sortable and searchable information. To implement this, I referred to the example provided i ...

Having trouble locating the custom interface name in a TypeScript custom npm package?

I have an Angular application in TypeScript that is built with webpack. I also have an npm package (hosted in Sinopia, not on npm) structured as follows: my-custom-npm-package - index.ts - studentStorage.ts - student.d.ts student.d.ts interface IStudent ...

Navigating through the file structure with systemjs-builder

My project is structured as follows: /node_modules /client |---/app | |---/app.module.ts | |---/main.ts |---/systemjs.config.js |---/index.html /server |---/server.js /tools |---/builder.js /package.json I am using angular2-rc5 I have exposed c ...

The RemoveAt(i) function will not eliminate

I am facing an issue with the removeAt(i) function in my code. It is not removing the element at the specified index. Can someone guide me on how to properly remove an element from an array? Here is the StackBlitz link for reference HTML <form [formGro ...

What is the best way to implement generics for a zip function in TypeScript?

I want to enhance this JS function by including types: function zip(array1, array2) { const length = Math.min(array1.length, array2.length); const result = []; for (let i = 0; i < length; i++) { result.push([array1[i], array2[i]]); } retur ...

Can a new record be created by adding keys and values to an existing record type while also changing the key names?

If I have the following state type, type State = { currentPartnerId: number; currentTime: string; }; I am looking to create a new type with keys like getCurrentPartnerId and values that are functions returning the corresponding key's value in Sta ...

What is the best way to update the environment configuration in an Angular application within an Nx monorepository?

Launched my experimental application on firebase-hosting. When I click the sign-up/sign-in button, it triggers the function 'signInWithPopup(auth, provider)'; A popup window appears with the message: "This site can’t be reached. 127.0.0.1 ref ...

Serving HTML from NodeJS instead of JSON

I have implemented two middleware functions import { NextFunction, Request, Response } from 'express'; const notFoundHandler = (req: Request, res: Response, next: NextFunction) => { const error = new Error(`Page Not Found - ${req.originalUr ...

Having trouble activating the ENTER key press event listener for the QuillJS editor in Angular 4 and above

I have been trying to set up an event listener for the ENTER key press in QuillJS using addBinding as described in the official documentation here. However, despite successfully configuring listeners for other keys like BACKSPACE, I am unable to get the EN ...

Angular module cannot be located

While working on implementing a chat feature for my project using sockJS and STOMP, I encountered several challenges with installing these two libraries. Despite attempting various methods such as installation from index.html, npm install, and manual downl ...