ChartJS ng 2-图表和注解插件:数据更新后注解不可见

xfyts7mz  于 2022-12-13  发布在  Chart.js
关注(0)|答案(2)|浏览(165)

我正在使用ng2-charts库创建一个图表,该图表使用来自REST API的数据进行更新。我使用annotation plugin。注解的数量发生了变化,因此仅更改现有注解是不够的-我需要能够在运行时添加/删除新注解。
当我一开始向图形选项添加注解时,注解呈现得很好,但在运行时,在更新数据和选项对象后,就看不到注解了。
稍后,我将注解添加到图形的选项中:

this.barChartOptions.annotation.annotations.push(
   {
                drawTime: 'beforeDatasetsDraw',
                type: 'box',
                xScaleID: 'x-axis-0',
                yScaleID: 'y-axis-0',
                xMin: tmpFirstBorder,
                xMax: tmpLastBorder,
                yMin: 0.5,
                yMax: 5,
                backgroundColor: 'rgba(71, 158, 245, 0.5)',
                borderColor: 'rgb(71,158,245)',
                onClick: function (e) {
                  console.log('Box', e.type, this);
                }
              }

然后更新数据,以便重新绘制图表:

this.barChartOptions = this.barChartOptions;
 this.barChartData = tempChartData;

图形重新绘制得很好,但没有注解。
我想这可能是图表选项不更新的问题,所以我尝试添加一个显式更新:

@ViewChild(BaseChartDirective) chart: BaseChartDirective;

[...]

this.chart.chart.update();

但无济于事。
有人知道我怎样才能正确地画出注解吗?谢谢。

o3imoua4

o3imoua41#

this.barChartOptions.annotation.annotations
不是数组。它是另一个对象,如示例中所示

const options = {
  plugins: {
    autocolors: false,
    annotation: {
      annotations: {
        line1: {
          type: 'line',
          yMin: 60,
          yMax: 60,
          borderColor: 'rgb(255, 99, 132)',
          borderWidth: 2,
        }
      }
    }
  }
};

因此,要添加一个新的注解,需要添加一个对象,而不是推送一个数组元素。

let annotationsCount = Object.entries(this.barChartOptions.annotation.annotations)

然后,您可以使用

this.barChartOptions.annotation.annotations[annotationsCount] = yourNewAnnotationObject

annotationCount可以是任何值。它只是新对象的键,如示例中的 line1。使用内部已有对象的数量只是一个建议。但是它必须是唯一的,否则将覆盖现有对象而不添加新对象

0qx6xfy6

0qx6xfy62#

您可以尝试设置drawTime属性

annotation: {
          drawTime: 'afterDatasetsDraw',
          annotations: [....]
        }

相关问题