【问题标题】:Showing every other label on yAxis canvas chartjs在 yAxis 画布 chartjs 上显示所有其他标签
【发布时间】:2017-12-15 03:28:49
【问题描述】:

我想知道有没有一种方法可以控制要显示的标签数量 - 我知道有 stepSize 功能,但它是数字的。我正在寻找像interval:3 这样的东西,所以它会在图表上每隔三个标签显示一次。

options: {
  scales: {
      xAxes: [{
        ticks: {
          beginAtZero:true,
          max: 100
        }
      }],
        yAxes: [{
          ticks: {
          }
        }]
    }
}

这就是我渲染图表的方式:

html:

<div class="chart-container" style="position: relative; height:20vh; width:40vw">
      <canvas id="chartGraph"   baseChart [colors]="colorsOverride" [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="false" [chartType]="barChartType">
      </canvas>
</div>

在我的 component.ts 我有:

barChartOptions: any = {
    scaleShowVerticalLines: false,
    responsive: true,
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero:true,
          max: 100
        }
      }],
        yAxes: [{
          ticks: {

          }
        }]
    },
      tooltips:{
        mode: 'point'
      }
  };
  barChartLabels: string[] = [];
  barChartType: string = 'horizontalBar';
  barChartLegend: boolean = false;
  barChartData: any[] = [];
  data: any;

  colorsOverride: Array<Color> = [{
    backgroundColor: '#6aaf6a',
    hoverBackgroundColor: 'purple'
  }];

    getChartData(link:string){
        this.service.getQuery(link).subscribe(
            data => {
                this.data = data;
                this.barChartLabels = this.data.map(x => x.display);
                this.chartData = this.data.map(x => x.value);
                this.barChartData = [{data: this.chartData, label:'sample' }];
            }
        );
    }

【问题讨论】:

  • @ℊαα这更像是一个数字间隔,但我正在寻找标签间隔,所以就像它显示一月、三月、五月的标签一样......但条形图将显示每个月。 (基于您的示例)
  • @ℊαα是的 - 你使用了什么属性?

标签: canvas charts ng2-charts


【解决方案1】:

来源:Limit labels number on Chart.js line chart

George 提供的示例将每隔一个标签留空。

 var options =  {  
     scales: {
        xAxes: [{
            afterTickToLabelConversion: function(data){

                var xLabels = data.ticks;

                xLabels.forEach(function (labels, i) {
                    if (i % 2 == 1){
                        xLabels[i] = '';
                    }
                });
            } 
        }]   
    }
}

要保留 X 轴上的第一个值,然后是第四个、第八个等,您可以将 if 语句更改为:

if (i % 4 != 0){ 
    xLabels[i] = ''; 
}

该解决方案也适用于 yAxes 选项。变量名 xLabels 不是 chartjs 的一部分,更改它不会造成任何损害。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多