диаграмма. js динамически устанавливаемые значения рекомендуемых мин. и предлож. макс. на основе значений массива - PullRequest
0 голосов
/ 06 августа 2020

проблема

делает диаграмму нескольких кривых более читаемой - особенно этот светло-зеленый, который в некоторых местах имеет такое же значение и прямой

enter image description here

how to solve this problem

Set min and max values of y axis iot make more space above and below curve. This values may be set by this code:

public lineChartOptions:any = {            
    scales: {
        yAxes: [{
          id: 'SeriesA',
          position: 'left',
          ticks: {
            suggestedMin: 0,
            suggestedMax: 100
          }
        }]
    }
};

Chart.js makes it automatically to calc this min and max value, however in some places I would like to extend it (by setting suggestedMin and suggestedMax values). Values should be based on min value of array (reduced by 10%) and max value of array (enlarged by 10%).

For such an example data I wold like to get min value of Y axis of 54, and max of 66

public seriesA: Array = [59.023, 59.023, 59.034, 59.034, 59.034, 59.039, 59.05, 59.061, 59.088, 59.104];
    
public minMaxSeries: Array = [0, 0];

 ngOnInit(): void {
    // calc min and max value of array
    this.minMaxSeries[0] = this.seriesB.reduce((prev, curr) => {
      return Math.min(prev, curr);
    });
    this.minMaxSeries[1] = this.seriesB.reduce((prev, curr) => {
      return Math.max(prev, curr);
    });
  
    // set values of min and max to the nearest integer value depends on its positive and negative values
    if (this.minMaxSeries[0] >= 0) {
      this.minMaxSeries[0] = Math.ceil(this.minMaxSeries[0] - 0.1 * this.minMaxSeries[0]);
    } else {
      this.minMaxSeries[0] = Math.floor(this.minMaxSeries[0] + 0.1 * this.minMaxSeries[0]);
    }
    if (this.minMaxSeries[1] >= 0) {
      this.minMaxSeries[1] = Math.ceil(this.minMaxSeries[1] + 0.1 * this.minMaxSeries[1]);
    } else {
      this.minMaxSeries[1] = Math.floor(this.minMaxSeries[1] - 0.1 * this.minMaxSeries[1]);
    }
    console.log(this.minMaxSeries)
  }

my code: Angular проект

1 Ответ

1 голос
/ 08 августа 2020

Изменение значений minMaxSeries не изменяет lineChartOptions. Если вы добавите console.log(this.lineChartOptions); в конце ngOnInit(), вы увидите, что suggestedMin и suggestedMax по-прежнему имеют нулевое значение.

Чтобы решить вашу проблему, вы должны установить параметры непосредственно на lineChartOptions следующим образом:

this.lineChartOptions.scales.yAxes[0].ticks.suggestedMin = min;
this.lineChartOptions.scales.yAxes[0].ticks.suggestedMax = max;

Метод ngOnInit() можно упростить, как показано ниже.

ngOnInit(): void {
  this.lineChartOptions.scales.yAxes[0].ticks.suggestedMin = Math.floor(Math.min(...this.seriesB));
  this.lineChartOptions.scales.yAxes[0].ticks.suggestedMax = Math.ceil(Math.max(...this.seriesB));
}  

Обратите внимание на ваш измененный StackBlitz .

...