【问题标题】:ng2-charts: extra margin on axisng2-charts:轴上的额外边距
【发布时间】:2020-05-10 22:13:05
【问题描述】:

我是在我的应用程序中使用 ng2-charts 的新手,我想知道是否可以将 Y 轴的最大值增加 5,这样我的条形图的顶部就不会一直到达顶部的图表。目前,当我的最大值为 90 时,我的 Y 轴的最大值也是 90,这会导致一些视觉上不愉快的重叠。

我目前使用的是文档中的默认代码,如下:

public barChartOptions: ChartOptions = {
    responsive: true,
    scales: { xAxes: [{}], yAxes: [{}] }
  };

  public barChartLabels: Label[] = [
    '2006',
    '2007',
    '2008',
    '2009',
    '2010',
    '2011',
    '2012'
  ];
  public barChartType: ChartType = 'bar';
  public barChartLegend = true;

  public barChartData: ChartDataSets[] = this.fetchData();

  public changeChart(): void {
    this.barChartType = this.barChartType === 'bar' ? 'line' : 'bar';
  }

【问题讨论】:

标签: angular charts ng2-charts


【解决方案1】:

ngOnInit 方法中,您可以计算在任何数据集中找到的最大值。

const allValues = this.barChartData.flatMap(ds => ds.data);
const maxValue = Math.max(...allValues);

然后定义图表options 并包含yAxes.tick.max,给它一个略大于maxValue 的值。

yAxes: [{
  ticks: {
    max: Math.ceil(maxValue * 1.05)
  }
}]

整个 ngOnInit 方法如下所示:

ngOnInit() {
  const allValues = this.barChartData.flatMap(ds => ds.data);
  const maxValue = Math.max(...allValues);
  this.barChartOptions = {
    responsive: true,
    scales: {
      yAxes: [{
        ticks: {
          max: Math.ceil(maxValue * 1.05)
        }
      }]
      }
  };
}

请看看这个StackBlitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2017-11-05
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多