【问题标题】:ng2-charts and annotation plugin: annotations not visible after data updateng2-charts 和注解插件:数据更新后注解不可见
【发布时间】:2021-01-29 23:35:57
【问题描述】:

我正在使用ng2-charts 库创建一个使用来自 REST API 的数据进行更新的图表。我使用annotation plugin。注解的数量发生了变化,因此更改现有注解是不够的 - 我需要能够在运行时添加/删除新注解。

当我在开始时向图形选项添加注释时,注释呈现得很好。但是在运行时,更新数据和更新options对象后,就看不到注解了。

稍后,我在图表的选项中添加注释:

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();

但无济于事。

有谁知道如何正确绘制注释?谢谢。

【问题讨论】:

    标签: typescript chart.js angular8 ng2-charts


    【解决方案1】:

    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 之类的新对象的键 使用内部已有对象的数量只是一个建议。 但是它必须是唯一的,否则你会覆盖现有的而不是添加新的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 2023-03-21
      • 2016-12-28
      • 2017-09-03
      • 1970-01-01
      相关资源
      最近更新 更多