简体   繁体   中英

How to set static labels for ng2-charts bar charts?

I am using ng2-charts. I have an array of data. I am printing day values in x-axis and marks in the y-axis. Problem is, if I have data only for Tue and Wednesday then it's showing only two but I want like static x-axis (Sun-Sat). As shown below

What I currently have:

条形图上 2 个条形图(星期一为蓝色,星期二为黄色)的屏幕截图

What I want to get:

条形图上 2 个条形图(星期二为蓝色,星期三为黄色)的屏幕截图

HTML

<div style="display: block" *ngIf="barChartData">
  <canvas baseChart width="400" height="180" style="margin-left:5%;margin- 
top: 5%;" [datasets]="barChartData"
[labels]="barChartLabels" [options]="barChartOptions" 
[legend]="barChartLegend" [chartType]="barChartType"
(chartHover)="chartHovered($event)" [colors]="chartColors" 
(chartClick)="chartClicked($event)"></canvas>
</div>

TS

this.barChartLabels = this.days; //Have week days like[tue,wed]
setTimeout(() => {
 this.barChartData = [
   { data: this.marks },
 ]
})

To achieve the solution please update your code like below.

HTML

 <div>
        <div style="display: block">
           <canvas baseChart
                [datasets]="barChartData"
                [labels]="barChartLabels"
                [options]="barChartOptions"
                [legend]="barChartLegend"
                [chartType]="barChartType"
                (chartHover)="chartHovered($event)"
                (chartClick)="chartClicked($event)"></canvas>
         </div>
      <button (click)="randomize()">Update</button>
    </div>

TS

export class AppComponent {

    public barChartOptions:any = {
        scaleShowVerticalLines: false,
        responsive: true
    };
  public barChartLabels:string[] = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  public barChartType:string = 'bar';
  public barChartLegend:boolean = true;

  public barChartData:any[] = [
    {data: [0, 0, 80, 81, 0, 0, 0], label: 'Graph 1'},
  ]
}

Here Working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM