首页 > 解决方案 > 如何在使用 ng2-chart 构建的散点图中标记点

问题描述

我使用 ng2-chart 构建了这个散点图: 在此处输入图像描述 我想要的是:在图中的每个黑点旁边显示一个“名称”。

Chart.component.html:

<!-- chart.js -->
<div style="display: block;">
  <canvas
    baseChart
    [datasets]="scatterChartData"
    [options]="scatterChartOptions"
    [chartType]="scatterChartType"
  >
  </canvas>
</div>
<div class="jumbotron jumbotron-fluid">
  <div class="container">
    <div class="typo-line">
    <h4><p class="category"><b>Légende</b></p></h4>
  </div>
    <p class="text-primary">
      R-1 Tremblement de terre
    </p>
    <p class="text-primary">
      R-2 Température et humidité
    </p>
  </div>
</div>

Chart.component.ts:创建黑点的代码:

public scatterChartType: ChartType = "scatter";
  constructor(private data: AnalyseRisqueService) {}
  probaGraviteValuesIndexedByRow:number[][]=[]
  ngOnInit() {
     this.data.currentProbaGraviteValuesIndexedByRow.subscribe(receivedProbaGraviteValuesIndexedByRow=>
      (this.probaGraviteValuesIndexedByRow=receivedProbaGraviteValuesIndexedByRow)
      )
    setTimeout(() => {
      this.chart.chart.data.datasets[0].data = [
        { x: this.probaGraviteValuesIndexedByRow[0][0], y: this.probaGraviteValuesIndexedByRow[0][1] },
        { x: this.probaGraviteValuesIndexedByRow[1][0], y: this.probaGraviteValuesIndexedByRow[1][1] },
        { x: this.probaGraviteValuesIndexedByRow[2][0], y: this.probaGraviteValuesIndexedByRow[2][1] },
        { x: this.probaGraviteValuesIndexedByRow[3][0], y: this.probaGraviteValuesIndexedByRow[3][1] },
        { x: this.probaGraviteValuesIndexedByRow[4][0], y: this.probaGraviteValuesIndexedByRow[4][1] },
        { x: this.probaGraviteValuesIndexedByRow[5][0], y: this.probaGraviteValuesIndexedByRow[5][1] },
      ]
      this.chart.chart.update();
  }, 1000);
  }

标签: angularchart.jsng2-charts

解决方案


点的工具提示是使用options画布的绑定提供的。

将工具提示作为回调添加到您的scatterChartOptions对象,就像在您的 TS 文件中一样:

public scatterChartOptions: ChartOptions = {
    responsive: true,
    tooltips: {
      callbacks: {
        label: (item, data) => 
        {
          console.log(item);
          return 'Label: ' + item.xLabel + ' ' + item.yLabel
        }
      }
    }
  };

这应该显示一个带有 x 和 y 值的简单标签。

看看这个有效的 StackBlitz。


推荐阅读