如何使用 chartjs-plugin-annotation 在图表上创建一条线

How to create a line on a chart using chartjs-plugin-annotation

我正在使用 angular、Chartjs 和 ng2-charts 在我的项目中创建图表。 我正在尝试按照 GitHub repository 上提供的说明制作中间线。问题是,当我添加此代码时,它 "undisplays"(我不确定这是一个英文单词)chart.Here 是我想要重现的内容:

这是我的代码:

public lineVistaChartOptions:any = {
    responsive: true,
    annotation:{

  drawTime: 'afterDatasetsDraw', // (default)


  events: ['click'],


  dblClickSpeed: 350, // ms (default)
  annotations: {
    type: 'line',


    drawTime: 'afterDatasetsDraw',


    id: 'a-line-1',


    mode: 'horizontal',

    // ID of the scale to bind onto
    scaleID: 'y-axis-0',


    value: 50,


    endValue: 100,


    borderColor: 'red',


    borderWidth: 2,


    borderDash: [2, 2],


    borderDashOffset: 1,

    label: {

      backgroundColor: 'rgba(0,0,0,0.8)',


      fontFamily: "sans-serif",


      fontSize: 12,


      fontStyle: "bold",


      fontColor: "#fff",


      xPadding: 0,


      yPadding: 0,


      cornerRadius: 6,


      position: "center",


      xAdjust: 0,



      yAdjust: 0,


      enabled: true,


      content: "Test label"
    }


  }
}

};

与文档完全相同。

您实际上不需要 set/use 所有属性。仅设置满足您的要求所需的那些。因此,设置以下属性应该足以绘制水平线:

annotation: {
   annotations: [{
      type: 'line',
      id: 'hLine',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: 3,  // data-value at which the line is drawn
      borderWidth: 2,
      borderColor: 'black'
   }]
}

另外,注意 annotations 属性 不是只是一个对象,它一个对象数组。