Arrange and conceal legendary items based on their values using Chartjs in Angular

Is there a way to hide the legend or not display it when the value supplied is 0, and also order items in ascending order?

export class DoughnutChartComponent {

  doughnutChartLabels: Label[] = ['CR1', 'CR2', 'CR3', 'CR4', 'CR5', 'BOX', 'APP', 'Center 8', 'Center 9'];
  doughnutChartData: number [] = [55, 25, 20, 0, 54, 33, 0, 70, 88];
  doughnutChartOptions: ChartOptions = { legend: {
      display: true,
      position: 'right',
      fullWidth:false,
      reverse: false,
      labels: {
        usePointStyle: true,
        boxWidth: 10,
        padding: 7,
        fontSize: 18,
        fontColor: '#003457',
        fontStyle: 'bold',
      },
      },
     cutoutPercentage: 70,
    };
  doughnutChartType: ChartType = 'doughnut';
  doughnutChartColor: Colors[] = [{
    backgroundColor: [
      '#2E9FE0',
      '#9CCA32',
      '#255FCC',
      '#B746A6',
      '#FF9232',
      '#03B075',
      '#E5D844',
      '#45D2E4',
      '#E0489A'
    ]
  }] ;
}

I have been searching for a solution to this issue without success. Any help would be greatly appreciated.

Answer №1

If you want to customize the legend labels in your chart using chart.js, you can utilize the filter function as demonstrated below:

var options = {
  type: 'doughnut',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 0],
      borderWidth: 1,
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    legend: {
      labels: {
        filter: (legendItem, chartData) => {
          const index = chartData.labels.indexOf(legendItem.text)
          return chartData.datasets[0].data[legendItem.index] !== 0
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

Answer №2

You can accomplish this by using Array.filter() followed by Array.sort().

To simultaneously process doughnutChartLabels and doughnutChartData, you should wrap labels and values into objects first, and then unwrap them with Array.map().

You can achieve this by adding the following constructor to the DoughnutChartComponent:

constructor() {
  const temp = doughnutChartData
    .map((value, index) => ({ label: doughnutChartLabels[index], value: value }))
    .filter(obj => obj.value > 0)
    .sort((obj1, obj2) => obj1.value - obj2.value);
  doughnutChartLabels = temp.map(obj => obj.label);
  doughnutChartData = temp.map(obj => obj.value);
}

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

How to simulate keyboard events when a dropdown list is opened in an Angular application

Requirement- A situation arises where upon opening the dropdown menu, pressing the delete key on the keyboard should reset the index to -1. Steps to reproduce the issue: 1. Click on the dropdown and select an option from the menu. 2. Click on the dropdow ...

Extracting Information from a Table in Angular 7

Hi there, I'm new to this forum so if I break any rules, please let me know! I'm working with the code below in my app.component.html: <tr *ngFor="let item of items" (click)="getClient($event)"> <td> {{ item.nr }} </td> ...

The parent class has not been specified

I am facing an issue with my parent class, HTTPConnection, which I intend to use as a network utility class in order to avoid redundant code. However, when attempting to utilize it, the file core.umd.js throws an error stating Uncaught ReferenceError: HTTP ...

Server-Side Rendering will occur exclusively for the `/` url, but only upon reloading the landing page. This setup utilizes Angular 16, implements Lazy Loading, and runs

Whenever I run my Angular ionic application locally and refresh the pages (all of them), I notice these console logs popping up on my screen. However, once I deploy it on PM2 in a production environment, the console log only shows up for the home page. I ...

AgGrid's magical dropdown feature

Struggling to integrate a bootstrap-4 dropdown menu with AgGrid, I'm facing an issue where the data table overlaps the dropdown when the html is present. Attempts to increase the z-index have not yielded results. Below is the html code snippet: < ...

Discovering the clicked element within a QueryList<ElementRef> in Angular

Having a ElementRef(QueryList) of a group of dynamically created Table cells (td html elements) using ViewChildren, I have successfully debugged and verified the availability of the element set. When clicking on a specific td html element, a function is c ...

Issues with HttpTestingController's expectOne method arise when the actual request is contained within a promise

Currently, I am in the process of creating a unit test for a service that involves retrieving data from another service (which returns a Promise) and then making an HTTP GET request. To mock the HTTP request, I am utilizing HttpTestingController from @ang ...

angular contains vulnerabilities of a moderate severity level

I am encountering an issue while trying to set up the json server for a web application I am developing using Angular. Can someone provide assistance in resolving this problem? The following dependencies are at risk due to vulnerable versions: node_m ...

Utilizing Chart.js to extract and display specific data values from an external JSON file

I am currently engaged in a journey of self-exploration where I aim to create a chart depicting the number of anime shows with comedy or fantasy genres. The data for my chart will be sourced from an external JSON file (anime.json) on my computer. Initially ...

document.addEventListener versus $().on

Recently, I came across an odd behavior while trying to add event listeners to the document. Strangely, when adding listeners to HTMLElements, everything worked smoothly, but for some reason, adding a listener to the document did not have any effect. Howev ...

Struggling with inter-component communication in Angular without causing memory leaks

After researching different methods, it appears that the recommended way for unrelated Angular components to communicate is by creating a service and utilizing an RxJS BehaviorSubject. A helpful resource I came across outlining this approach can be found h ...

An issue has occurred: the property 'map' cannot be read as it is undefined

Encountered this unexpected error and struggling to understand the reason behind it.. I've been attempting to showcase events on angular-calendar: Error occurred in error_handler.ts:1 - ERROR TypeError: Cannot read property 'map' of unde ...

Having trouble with the disabled property in Angular 10? Learn how to properly use it and troubleshoot

---Update--- I had previously posted this question without receiving a solution. I came across a Github blog that mentioned the "isButtonDisabled" alone may not work and a function needs to be called instead. In my TypeScript code, I can only generate a b ...

Typescript gives you the ability to create a versatile writing interface that includes all

Think about this: interface Options { length?: number, width?: number } interface Action { performAction ({length, width}: Options): void } const myObject: Action = { performAction ({length, width}) { // do something without returning ...

Issue with Angular 9 Json pipe not showing decimal values

My JSON data looks like this: this.data = {"eoiStatistics": [ { "dateRange": { "explicitStartDate": "1997-01-01T00:00:00", "explicitEndDate": "2019-07-01T00:00:00" }, "outstandingApplicationCount": 0.0, "pendingApplicationCount": 24.0, " ...

Tips for passing data between two components in React Router and outlet without the need for higher order functions

In my project, I have developed two components: one is named <Flights/> and the other is called <FlightResults/>. The Flights component serves as a context provider for the entire application. const Flights = () => { return ( <Flig ...

Incorporate a boolean value into Ionic storage (Ionic 4) by adding a JSON object

I am looking to enhance my storage system by adding a special favorite feature. I have the ability to add multiple favorites to my storage, but only one can be designated as my top favorite! Take a look at this image for a visual representation of what I h ...

Incorporate a new element into a dynamic, responsive form using Angular

I’m struggling to create a nested reactive form in Angular 5. I can add items at one level successfully, but I’m having trouble adding items at the second level. ngOnInit() { this.orderForm = this.formBuilder.group({ customerName: '', e ...

What is the method for including a TabIndex property in a JSON file?

https://i.sstatic.net/ISi72.png I discussed the integration of HTML fields within a JSON file and highlighted how to utilize the TabIndex property effectively in JSON files. ...

Can we destruct and type the properties of a function parameter object that are already known?

Typescript playground Scenario: Creating a function that takes a single object with predefined properties, where we need to destructure and assign simultaneously. The following method works as intended: type OBJECT_PARAM = { pathname: string, routePa ...