Alan
Alan

Reputation: 69

Angular Overlapping bars using chart.js

I am trying to display a Stack Bar Chart on two datasets. The only issue is that once the graph is render the bars overlap making it difficult to distinguish between them (see example below). If the stacked property on the x-axis and y-axis is set to true the bars won't overlap anymore but they will be display in a way where bar B starts at the end of A. From the example below, how could I make bar B display more clearer so that it is easier to distinguish it from A. Maybe a property that hides pixels from bar A whenever B overlaps it.

enter image description here

Component A - ComponentA.ts

import { Component, HostListener } from '@angular/core';
import { service } from '../../..common/service';
import { ChartDataSets } from 'chart.js'

... Some Code...

@Component({
    selector: 'ComponentA',
    styleUrls: ['./ComponentA.css'],
    templateUrl: './ComponentA.html'
})

export class compA {

chartOptions: any = {
       scales: {
            xAxes: [{
                stacked: false, 
            }],
            yAxes: [{
                stacked: true,
           }]
       }
 };

... Some Code ...

arrayOne: Array<number>;

arrayTwo: Array<number>;

barChartData: ChartDataSets [] = []; 

barChartLabels = ["1", "2", "3", "4"]

constructor(private sw: Service){ }

 ... Some Code ...


 buildGraph(): void {
      this.barChartData = [
          { data: this.arrayOne, label: 'A', backgroundColor: '#fa9cb0' },
          { data: this.arrayTwo, label: 'B', backgroundColor: '#7b8dfd' }
      ]
 }

... Rest of Code ...

Component A - ComponentA.html

<div>
     <canvas> baseChart [datasets]="barChartData" [labels]="barChartLabels" [legend]="true" <chartType>="'horizontalBar'" [options]="chartOptions" </canvas> 
</div>

Upvotes: 1

Views: 1429

Answers (1)

wahab memon
wahab memon

Reputation: 2416

Not sure what issue you were facing, since you provided minimum details of your code. So, this is all I can give you as an answer, your options looks good, just the stack for x axis is false. This is how a sample of chart will look like or refer to stackblitz:

var chartInstance = new Chart(document.getElementById("chartJSContainer"), {
  type: 'bar',
  data: {

    labels: ["A", "B", "C", "D", "E", "G"],
    datasets: [{
      data: [40, 220, 15, 16, 24, 212],
      label: "Asia",
      backgroundColor: "#7b8dfd"
    }, {
      data: [86, 114, 10, 106, 107, 111],
      label: "Africa",
      backgroundColor: "#fa9cb0"
    }]
  },
  options: {
    indexAxis: 'y',
    scales: {
      xAxes: {
        stacked: false //Make it true to make the overlapping bars visible.
      },
      yAxes: {
        stacked: true
      }
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.js"></script>

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

Upvotes: 1

Related Questions