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

Generating a type definition from a JavaScript file

Looking to convert a .js file to a d.ts file, I've noticed that most resources on this topic are from 2 years ago How do you produce a .d.ts "typings" definition file from an existing JavaScript library? My question is, after 2 years, is there a simp ...

Utilizing OverlappingMarkerSpidifier in conjunction with sebm-angular2-google-map

I'm currently integrating OverlappingMarkerSpidifier using SebM Angular 2 Google Maps on angular2 2.0.0. After successfully loading the google maps API with the GoogleMapsAPIWrapper imported from the sebm module, I am running into an issue when execu ...

retrieve a collection of objects using Angular CLI

Hey there, I'm currently working on fetching data using a get request in Angular. My Apartment class is structured as follows: export class Apartment { id: number; address: string; constructor(id: number, name: string) { this.id = id; ...

Changing email case with Angular reactive forms upon submission

I have a reactive form that allows users to enter email addresses with uppercase characters before the '@' symbol. However, I need to convert a valid email address like '[email protected]' to '[email protected]' onSu ...

What impact does introducing a constraint to a generic type have on the inference process?

Let's take a look at this scenario: function identity<T>(arr: T[]) { return arr } identity(["a", "b"]) In the above code snippet, the generic type T is inferred as string, which seems logical. However, when we introduce a ...

Implementing an extended interface as an argument in a function

Here is the code snippet for analysis: interface IUserData { FirstName: string, LastName: string, Email: string, Password: string } interface IState extends IUserData { isSuccess: boolean } const state: IState = { FirstName: &apo ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

What is the process for generating an object type that encompasses all the keys from an array type?

In my coding journey, I am exploring the creation of a versatile class that can define and handle CRUD operations for various resources. The ultimate goal is to have a single generic class instance that can be utilized to generate services, reducer slices, ...

Programmatically setting focus in Ionic

In my Ionic and Angular component, I am attempting to programmatically set focus after the page has loaded. Here is the code: item.component.html: <ion-row> <ion-col col-5> <ion-item > <ion-label&g ...

Unable to execute unit tests while utilizing imports that are only for types

Check out this solution I have developed a library that includes both a component and a directive, resulting in an import cycle issue. Component import { Component } from '@angular/core'; @Component({ selector: 'lib-resizable', t ...

The error message "Value property is not found on the FilterMetadata type in the PrimeNG table" indicates that there is an issue with accessing the 'value'

While transitioning a module from Primeng 7 to Primeng 11 in conjunction with Angular 11, everything seems to be running smoothly on ng serve with all functionalities working as expected. However, upon building the project, I encounter an unexpected error. ...

Angular websocket failing to execute API post request

I am currently developing a demo application that involves making a POST API call. The main goal is to send a query via the POST API call and receive data from the API as a response. One key feature of this API is that it provides updated data every minute ...

Angular 6: A class with no 'default' modifier must explicitly specify a name

I am encountering this error in my ts.file, as I delve into the world of Angular/Ionic. Can anyone help identify the possible reasons for this? I have attempted multiple solutions to address it, but unfortunately, none have proven successful. import { Co ...

Issue with Rxjs switchMap function not correctly executing the provided function

Currently utilizing the Subject observable provided by rxjs. In my component, I have implemented two methods. Search search(terms: Observable<string>) { return terms.pipe( debounceTime(400), distinctUntilChanged(), switchMap(term => ...

What specific element is being targeted when a directive injects a ViewContainerRef?

What specific element is associated with a ViewContainerRef when injected into a directive? Take this scenario, where we have the following template: template `<div><span vcdirective></span></div>` Now, if the constructor for the ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

Firestore - Insert new entries into an array in an existing document using Typescript

After retrieving data from Firestore using Firebase and implementing pagination function, I encounter an issue when attempting to add the new values to an array. Specifically, TypeScript raises an error message when I try to invoke the setState hook. int ...

Exploring Blob functionality in TypeScript?

I defined a global Blob object: declare global { interface Blob { prototype: Blob; new (name: string, url: string): Blob; } } It is functioning correctly in this code snippet: export const blobToFile = (blob: Blob) => { let file: File | n ...

Checking if a date is before another date in MomentJS without considering the

Recently, I've been utilizing momentJS to identify future dates without a specific day. Below is the code I've been working with along with the outcome: moment('09/2010').isBefore(moment().format('MM/YYYY'), 'day') ...