[Chartjs]-Ng2-charts + How to customize the position of X axis labels?

2👍

I think this is help you. its working as you expecting.

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:

public barChartLabels:string[] = ['2006', '2007', '2008', '2009', '2010', '2011'];
  public barChartType:string = 'bar';
  public barChartLegend:boolean = true;


 public barChartOptions: any = {
    responsive: true,
    tooltips: {
      enabled: false
    },
    animation: {
      onComplete: function () {
        var ctx = this.chart.ctx;
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        var chart = this;
        var datasets = this.config.data.datasets;

        datasets.forEach(function (dataset: Array<any>, i: number) {
          ctx.font = "10px Arial";


          ctx.fillStyle = "Black";
          chart.getDatasetMeta(i).data.forEach(function (p: any, j: any) {
            ctx.fillText(datasets[i].data[j], p._model.x, p._model.y - 20);
          });

        });
      }
    },
    legend: {
      display: true,
      labels: {
        fontColor: '#4286f4',
        backgroundColor: '#4286f4'
      }
    },
    scales: {
     yAxes: [
      {
          display: true,
          ticks: {
            min: 0,
            max: 100,
            stepSize: 100,
          },
          gridLines: {
                offsetGridLines: false
            }
      }
    ],
  }
  }

  public barChartData:any[] = [
    {data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'}
  ];

  // events
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }

  public randomize():void {
    // Only Change 3 values
    let data = [
      Math.round(Math.random() * 100),
      59,
      80,
      (Math.random() * 100),
      56,
      (Math.random() * 100),
      40];
    let clone = JSON.parse(JSON.stringify(this.barChartData));
    clone[0].data = data;
    this.barChartData = clone;
  }

you can also check on link below:

Link

Leave a comment