Difficulty modifying the background color of a bar graph in Chart.js within an Ionic 2 Angular2 environment

I've been working with Chart.js in an Ionic2 and Angular2 hybrid app to create a stacked bar graph. However, I'm facing an issue where I can't seem to change the background color or fill color of the bars in the graph. Despite trying out all the examples and configurations provided on Chart.js documentation, the bars always end up defaulting to red and blue colors.

Here's a snippet of my code:

barChartOptions:any = {
    responsive: true,
    scales: {
      xAxes: [{
        categoryPercentage: 0.6,
        barPercentage: 1.0,
        stacked: true,
        ticks: {
          beginAtZero: true
        },
        gridLines: {
            color: "rgba(255,255,255,1.0)",
            zeroLineColor: "rgba(254,254,254, 1.0)"
        }
      }],
      yAxes: [{
        display: false,
        ticks: {
          beginAtZero: true
        }
      }]
    },
    legend: {
        display: false,
    }
};
barChartLabels:string[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
barChartType:string = 'bar';
barChartLegend:boolean = false;;

barChartData:any[] = [

    {
        fillColor:'rgba(255, 99, 132, 0.2)',
        borderColor: "rgba(10,150,132,1)",
        borderWidth: 5,
        data: [65, 59, 80, 81, 56, 55, 40], 
    },
    {
        backgroundColor: '#61ae37',
        data : [190,150,125,185,150,135,175]
    }
];  

The main problem lies within the fillColor and backgroundColor fields of the barChartData object.

I've attempted various other configurations from the documentation as well:

data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
    'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)',
    'rgba(255, 159, 64, 0.2)'
],
borderColor: [
    'rgba(255,99,132,1)',
    'rgba(54, 162, 235, 1)',
    'rgba(255, 206, 86, 1)',
    'rgba(75, 192, 192, 1)',
    'rgba(153, 102, 255, 1)',
    'rgba(255, 159, 64, 1)'
],
borderWidth: 1

Despite being able to change the border width, the border color remains unchanged. Additionally, I've experimented with the rectangle configuration but no luck there either.

The original code example I started with was this:

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 1,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [65, 59, 80, 81, 56, 55, 40],
        }
    ]
};

I suspect there might be some default configuration overriding my settings. Any assistance would be highly appreciated.

Answer №1

After some investigation, I discovered the issue at hand. My implementation includes the usage of ng2-charts, and their setup differs slightly. In their configuration, they utilize a [colors] attribute in the HTML markup to specify color choices. To address this, you need to create an additional object in your .ts file for colors that is separate from your chart options object.

barChartColors: any[] = [
    {
        backgroundColor:'rgba(255, 99, 132, 1)',
        borderColor: "rgba(10,150,132,1)",
        borderWidth: 5
    },
    {
        backgroundColor:'rgb(97 174 55, 1 )',
        borderColor: "rgba(10,150,132,1)",
        borderWidth: 5,
    }
]

In the HTML markup, it should appear as follows:

<base-chart class="chart"
           [datasets]="barChartData"
           [labels]="barChartLabels"
           [options]="barChartOptions"
           [colors]="barChartColors" <-----this is crucial
           [legend]="barChartLegend"
           [chartType]="barChartType"
           [responsive]='false'
           (chartHover)="chartHovered($event)"
           (chartClick)="chartClicked($event)">

           </base-chart>

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

Upgrading from Angular 10 to 13 resulted in an error that required adding 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas'. Although this fix was implemented, the issue still persists and the application remains broken

Here are a few examples of errors: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurred in the template of component ShochatactivestreamviewShellComponent. Error: src/app/money_makers/shochat_guts/shochat_content_creato ...

Guidelines for creating a binary release of Node.js with native modules

Currently, I am in the midst of exploring the world of Node.js projects, delving into different bundlers and various other components. One interesting concept that came to mind is the idea of bundling Node.js into a single binary for Linux, macOS, or Windo ...

Looking for someone who has successfully upgraded React Native code from version 0.59 to the most recent version

Is there a way to make my React Native project compatible with the latest version? I am facing a challenge in updating an old React Native project running on version 0.59.10 to the most recent version. Despite trying various methods, I have been unable to ...

Strategies for effectively mocking an Angular service: During Karma Jasmine testing, ensure that the spy on service.getShipPhotos is expected to be called once. In the test, it should

Currently, I am working on testing a function called getSingleShip in Angular 12 using Karma-Jasmine 4. The aim is to verify if this function is being called by another function named retrieveShip. However, the test results indicate that getSingleShip has ...

The Angular firestore is showing an error stating that the property 'toDate' is not found in the 'Date' type

I am currently working on converting a timestamp object from Firestore to a Date object in TypeScript by utilizing the toDate() method. import { AngularFirestore } from '@angular/fire/firestore'; ... constructor(private database?: AngularFirestor ...

How to import a page from a different component in the Next.js application router

I am currently utilizing the Next.js app router and have organized my folders as follows: app/ ├─ /companies/ │ ├─ page.tsx ├─ /administrators/ │ ├─ page.tsx My objective is to import the companies/page.tsx component into the admini ...

Utilizing Angular CLI configuration for End-to-End testing purposes

I'm currently in the process of updating an Angular CLI project to version 6 The issue I'm facing is that prior to version 6, I could run the command ng e2e -e=e2e and the tests would execute smoothly with the specified environment. However, in ...

What is the process for obtaining the ID of a selected node within ngx-graph?

Issue My challenge lies in using the ngx-graph library to create a flow chart within Angular 9. I am attempting to extract the id value of a node that has been clicked on. I have tried printing out "$event" and examining the PointerEvent object that appea ...

Utilizing Custom HTTP Headers in Angular 2 to Enhance Request Handling

Within my Angular 2 project, I am implementing the use of Http (@angular/http) to communicate with my API. In order for these requests to be successful, specific headers, including a JWT header, must be included in each API request. My goal is to have an ...

Creating an Angular production build without the need for devDependencies installed

I am currently in the process of setting up a Docker container for building my Angular app in production. I am using npm and I only want to include dependencies, not devDependencies. This is what I have so far: npm install --only=prod ng build project-na ...

connect validation of the form to a separate component from the current one

Currently, I am working on creating a searchable-dropdown component that I intend to use in multiple components. However, I am facing an issue with binding form validation to this component. For instance, I have a form for creating a user and I need to bi ...

Utilizing variables for Protractor command line parameters

I am struggling to make variables work when passing parameters as a string in my code. Conf.ts params: { testEnvironment: TestEnvironment.Prod, }, env.ts export enum TestEnvironment { Dev = 'dev', QA = 'qa', Prod ...

Angular Image Cropping: A How-To Guide

I have been on the lookout for an Angular plugin that allows me to crop images before uploading them to the database. Despite spending all day searching, I have not been able to find a suitable plugin that meets my requirements. What I need specifically i ...

My requests and responses will undergo changes in naming conventions without my consent or awareness

Initially, I wrote it in a somewhat general manner. If you require more information, please let me know! This is how my C# class appears when sent/received on the frontend: public class Recipe : ICRUD { public Guid ID { get; set; } ...

Decrease the gap between the ticks on a horizontal bar chart in ChartJS

Currently, I am utilizing the horizontal bar chart feature from chartjs and encountering an issue with the chart appearing too large. In addition, there is a notable gap between the ticks on the xAxis (as shown in the attached image). Does anyone know how ...

Updating data in Angular2+ components outside of the router outlet component area

<div><SearchProjects></SearchProjects></div> <div> <router-outlet></router-outlet> </div> When the search content is updated, I need to refresh the data for the router-outlet component accordingly. Init ...

Use the rowTemplate in a Kendo grid without replacing the existing one

I am currently utilizing Angular 1.4 with TypeScript and Kendo UI (employing angular directives). My goal is to create a RowTemplate for each row that dynamically changes the color based on a specific property of the item. While I am aware of jQuery solu ...

Surprising Outcome when Dealing with Instance Type - Allowing extra properties that are not explicitly stated in the type

I've come across an issue with the InstanceType Utility Type. I am trying to create a function that takes a class constructor and an instance of that class. For instance: export type Class<T=any> = { new(...args: any[]): T; }; function acceptC ...

Using TypeScript and React: Implementing interfaces based on props conditions

I am currently designing a component that must either receive a prop named text or children, but not both or neither. ✓ Allow <NotificationBar text="Demo"/> <NotificationBar>Demo</NotificationBar> ✗ Disallow <NotificationBar/&g ...

Guide on utilizing map function and reassigning the value

I am facing a challenge with a list of books that have IsEnable defaulting to False. During onInit(), I need to check each book to see if it is enabled. I was considering using an rxjs map and calling the getEligibleBooks() function within the map, but I ...