Steps for personalizing the dataset on a PrimeNG bar graph

I'm currently working with primeng in an Angular project and I need to create a bar chart where the last two horizontal bars have different colors.

Right now, the last two bars are incorrectly being assigned to represent dogs and cats. My goal is to adjust the graph so that the orange bars correspond to tiger and lion instead of dog and cat.

Due to restrictions on StackOverflow, I am unable to upload a picture directly. However, you can view the example image on this external hosting site: https://ibb.co/jZyxddC

Below is the component code snippet:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-status-logs-graph',
  templateUrl: './status-logs-graph.component.html',
  styleUrls: ['./status-logs-graph.component.scss']
})
export class StatusLogsGraphComponent implements OnInit {

  basicData: any;
  basicOptions: any;

  constructor() { 
      this.basicData = {
    labels: ['dog', 'cat', 'hamster', 'lizard', 'tiger', 'lion'],
    datasets: [
        {
            label: 'Domestic Animals',
            backgroundColor: '#42A5F5',
            data: [ 32, 54, 21, 11]
        },
        {
            label: 'Wild Animals',
            backgroundColor: '#FFA726',
            data: [28, 48]
        }
    ]
};
 }

  ngOnInit(): void {

}
}

Answer №1

Primeng utilizes chartjs as its underlying framework. For detailed documentation, please refer to this link.

When working with chartjs, you have the flexibility to define custom colors for each bar in your chart. One approach is to group all animals under a single dataset and assign specific colors to each animal. However, it's important to note that hiding the default legend may be necessary as it will display generic information when using a single dataset. You can design a customized legend using HTML/CSS if needed. Below is a complete example:

var basicData = {
    labels: ['dog', 'cat', 'hamster', 'lizard', 'tiger', 'lion'],
    datasets: [
        {
            data: [ 32, 54, 21, 11, 28, 48],
            backgroundColor: [
                '#42A5F5',
                '#42A5F5',
                '#42A5F5',
                '#42A5F5',
                '#FFA726',
                '#FFA726'
            ]
        }
    ]
};
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: basicData,
    options: {
        plugins: {
            legend: {
                display: false
            }
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="75e6ede4f7e1bbeff6abbaf6ece3">[email protected]</a>/dist/chart.min.js"></script>
<canvas id="myChart"></canvas>

However, this method may not be scalable for adding more data in the future. An alternative approach involves storing all data in an array and dynamically combining datasets. This allows for easier addition of new animals. Here is an illustration:

var animals = [
    {
        name: 'dog',
        data: 32,
        type: 'domestic'
    },
    {
        name: 'cat',
        data: 54,
        type: 'domestic'
    },
    {
        name: 'hamster',
        data: 21,
        type: 'domestic'
    },
    {
        name: 'lizard',
        data: 11,
        type: 'domestic'
    },
    {
        name: 'tiger',
        data: 28,
        type: 'wild'
    },
    {
        name: 'lion',
        data: 48,
        type: 'wild'
    }
];
var labels = [];
var data = [];
var colors = [];
for(var i = 0; i < animals.length; i++){
    labels.push(animals[i].name);
    data.push(animals[i].data);
    if(animals[i].type === 'domestic'){
        colors.push('#42A5F5');
    }
    else{
        colors.push('#FFA726');
    }
}
var basicData = {
    labels:labels,
    datasets: [
        {
            data: data,
            backgroundColor: colors
        }
    ]
};
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: basicData,
    options: {
        plugins: {
            legend: {
                display: false
            }
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5102030a191f550104405906101b">[email protected]</a>/dist/chart.min.js"></script>
<canvas id="myChart"></canvas>

Answer №2

To hide null values in PrimeNG charts, simply utilize the Chart.js skipNull property and assign it a value of true.

(It's worth noting that all PrimeNG charts are built on top of the Chart.js library).

Answer №3

Are you looking to create separate horizontal bar charts for domestic animals and wild animals, with the domestic animal bars in different colors?

If so, I recommend utilizing Ngx-charts. You can find a helpful guide at the following link:

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

The "export 'ɵɵcomponentHostSyntheticListener' (imported as 'i0') was not found in '@angular/core" error occurred during the Angular build

Trying to set up an Angular application with clarity UI. Using Angular version 10.1.1 and after adding clarity, encountering build errors. ERROR in ./node_modules/@clr/angular/esm2015/utils/animations/expandable-animation/expandable-animation.js 33:8-43 &q ...

The protractor tool is unable to recognize an Angular component when it is displayed on the page

I have implemented end-to-end (e2e) testing on my project, but I am facing issues that are causing my tests to fail. Below is a snippet of my app.po.ts file: import { browser, by, element } from 'protractor'; export class AppPage { public b ...

NPM installation stalls only when attempting to install the specific package, ts-jest

https://i.stack.imgur.com/Cvon1.png I've encountered an issue while trying to set up ts-jest in a new project. Here's what I've tried: $ mkdir test && cd test $ npm init -y $ npm install ts-jest Despite being able to install other ...

Loading external templates in Angular2 with Webpack2

Attempting to integrate ngtemplate-loader in a project using AngularJs 2 and Webpack 2 is proving challenging. While this setup has been successful in Angular 1.x projects with Webpack 1.x, it encounters an error when running in the browser: Uncaught Type ...

The API code runs smoothly in Angular, but hits a snag when used in Ionic

Here is the API code I used to connect my application to Zoho Creator: <form method="POST" action="https://creator.zoho.com/api/batool4/xml/myapp/form/form1/record/add"> <input type="hidden" name ="authtoken" value="14e8d1c6acf83682cd9622986f0f7 ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

The function is failing to return the expected value received from the observable subscription

I am attempting to verify the existence of a user in an Angular's in-memory API by validating their username. The function checkUsernameExists(username) is supposed to return an Observable<boolean> based on whether the API responds with undefine ...

Stop the MatSort feature from activating when the space key is pressed in Angular Material

I am currently using angular material tables and have implemented filters for each column. The filter inputs are located in the row header of each column, which is working fine. However, I am facing an issue where whenever I type and press the space key, ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined: controller async createReferralUrls() { this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referral ...

Is it possible to dynamically close the parent modal based on input from the child component?

As I follow a tutorial, I am working on importing the stripe function from two js files. The goal is to display my stripe payment in a modal. However, I am unsure how to close the modal once I receive a successful payment message in the child. Below are s ...

Encountering an issue with setting up MikroORM with PostgreSQL due to a type

I'm currently working on setting up MikroORM with PostgreSQL, but I've encountered a strange error related to the type: Here is the code snippet: import { MikroORM, Options} from "@mikro-orm/core"; import { _prod_ } from "./consta ...

What causes Angular2 to detect both reference changes and primitive changes even when the OnPush flag is enabled?

Take a look at this code snippet import {Component, OnInit, Input, OnChanges, DoCheck, ChangeDetectionStrategy} from 'angular2/core' @Component({ selector: 'child1', template: ` <div>reference change for entire object: { ...

Angular version 6 and its routing functionality

Hey there, I need some help with setting up routers in my Angular app. Here is the code from my files: import {NgModule} from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const APP_ROUTES: Routes = [ {pa ...

Encountered an error while attempting to install the @typescript-eslint/eslint-plugin

After starting the installation process for eslint plugins, I encountered an issue with @typescript-eslint/eslint-plugin. The plugin requires installation using--legacy-peer-deps, but this approach may introduce potential bugs by accepting an incorrect an ...

Utilizing ES6 Promises in Mongoose with Typescript to Create a Seamless Chain

When attempting to chain ES6 promises with Mongoose 4.5.4, I encountered an error in Typescript. public static signup(req: express.Request, res: express.Response) { UserModel.findOne({ email: req.body.email }).exec() .then(existingUser => { ...

Utilizing the functionalities provided by node.js, I came across an issue and sought out a solution for the error message "TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a function"

I have created a project centered around {typescript, react, electron, gaea-editor}. During an event, I utilized fs.writeFile() but encountered an error. The specific error message was: TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a functi ...

Exploring the Issue with SWR Hook in Next.js using TypeScript

Seeking assistance with the SWR hook as I navigate through some challenges while attempting to use it effectively. This time, the issue appears to be minor. The objective is to set a breakpoint in my API to retrieve data, using axios. The problem arises ...

Troubleshooting: Angular add/edit form issue with retrieving data from a Span element within an ngFor loop

I am currently working on an add/edit screen that requires submitting a list, among other data. The user will need to check 2-3 checkboxes for this specific data, and the saved record will have multiple options mapped. Here is what the HTML looks like: &l ...

What is the best way to specify the return type in TypeScript when there is a possibility of multiple types?

I'm currently working on implementing type definitions for an Axios API client but I’m struggling with indicating to the compiler the specific return type that I am expecting. Here is a simplified example: import axios, { AxiosResponse } from "axi ...