【问题标题】:How can I draw a horizontal reference line in chart.js?如何在 chart.js 中绘制水平参考线?
【发布时间】:2022-06-30 02:26:20
【问题描述】:

我想在特定值处绘制水平参考线。

数据格式为:

{
      "Close": 15638.8,
      "Date": "2022-06-21T10:00:00.000Z",
      "High": 15707.25,
      "Low": 15419.85,
      "Open": 15455.95,
      "Volume": 0,
      "id": 36
    }

这是我目前所想的。我不确定如何使用 refLines 属性。

 var dataReqdFormat = {
    labels: [],
    datasets: [{
      data: [],
      label: "Nifty",
      fill: true,
      borderColor: (ctx) => {
        const data = ctx.chart.data.datasets[ctx.datasetIndex].data;
        return data[0] >= data[data.length - 1] ? 'red' : 'green'
      }
    }]
  };

感谢任何帮助。

【问题讨论】:

    标签: charts chart.js chart.js2 chart.js3


    【解决方案1】:

    您可以为此使用annotation plugin

    var options = {
      type: 'line',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          borderColor: 'pink'
        }]
      },
      options: {
        plugins: {
          annotation: {
            annotations: {
              line: {
                type: 'line',
                yMin: 16,
                yMax: 16,
                borderWidth: 2,
                borderColor: 'red'
              }
            }
          }
        }
      }
    }
    
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.4.0/chartjs-plugin-annotation.js"></script>
    </body>

    【讨论】:

      猜你喜欢
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      相关资源
      最近更新 更多