簡體   English   中英

在 v2 上的 chart.js 中的圖表上繪制水平線

[英]Draw horizontal line on chart in chart.js on v2

我使用chart.js繪制了一個折線圖。 對於標簽和數據集,我從數據庫中獲取值。 我是 chart.js 及其非常強大的庫的新手,但我無法完全理解它。 我想繪制多條水平線。 就像數據集的平均值,標准偏差和最小值和最大值一樣。 我已經在 stackoverflow 中嘗試過這個問題,但這些問題出現了錯誤,或者可能是我無法理解工作。 這是我的 chart.js 代碼

function display_graph(id, label, data) {
var ctx = document.getElementById(id);
var data = {
    labels: data.labels,
    datasets: [
        {
            label: label,
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderWidth: 1,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: data.assay_value,
            spanGaps: false
        }
    ]
};

//options
var options = {
    responsive: true,
    title: {
        display: true,
        position: "top",
        text: label,
        fontSize: 18,
        fontColor: "#111"
    },
    legend: {
        display: true,
        position: "bottom",
        labels: {
            fontColor: "#333",
            fontSize: 16
        }
    }
};
var Blanks_Chart=null;
Blanks_Chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: options
});}

您可以使用chart.js 注釋插件輕松地在圖表上繪制線條,而無需手動在畫布中渲染像素(舊方法會給您帶來錯誤)。 請注意,該插件由與 chart.js 相同的團隊創建/支持,並在chart.js 文檔中提及。

這是一個示例代碼筆,演示在圖表上創建一條線。

添加插件后,您只需在圖表配置中設置annotation屬性即可。 這是一個例子。

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["January", "February"],
    datasets: [{
      label: 'Dataset 1',
      borderColor: window.chartColors.blue,
      borderWidth: 2,
      fill: false,
      data: [2, 10]
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js Draw Line On Chart'
    },
    tooltips: {
      mode: 'index',
      intersect: true
    },
    annotation: {
      annotations: [{
        type: 'line',
        mode: 'horizontal',
        scaleID: 'y-axis-0',
        value: 5,
        borderColor: 'rgb(75, 192, 192)',
        borderWidth: 4,
        label: {
          enabled: false,
          content: 'Test label'
        }
      }]
    }
  }
});

如果您正在使用NPMchartjs-plugin-annotation.js ,重要的事情 - 您可能會忘記,是注冊插件。

所以首先你安裝了 npm 包(這里是React ):

npm i react-chartjs-2                (depends on your framework)
npm i chartjs-plugin-annotation      (always required)

請參閱Vue.jsAngular以了解其依賴於框架的包。

選項 1:全局插件注冊

import { Line } from 'react-chartjs-2';
import Chart from 'chart.js';
import * as ChartAnnotation from 'chartjs-plugin-annotation';

Chart.plugins.register([ChartAnnotation]); // Global

// ...
render() {
    return (
        <Line data={chartData} options={chartOpts} />
    )
}

選項 2:每個圖表插件注冊

import { Line } from 'react-chartjs-2';
import * as ChartAnnotation from 'chartjs-plugin-annotation';

// ...
render() {
    return (
                                                   {/* per chart */}
        <Line data={chartData} options={chartOpts} plugins={[ChartAnnotation]} />
    )
}

chartData相當於data: { section 和chartOpts to options: { from jordanwillis answer 有關更多信息,請參閱github 帖子。

chart.js 還有許多其他插件可用

如果要繪制閾值線,最簡單的方法是使用混合折線圖。

注意:制作一個填充閾值的數組,長度應與您的數據集相同。

var datasets = [1, 2, 3];
var ctx = document.getElementById('chart').getContext('2d');
var thresholdValue = 2;
var thresholdHighArray = new Array(datasets.length).fill(thresholdValue);
var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                {datasets}, thresholdHighArray]
            },         
            options: {
                responsive: true,
                legend: {
                    position: 'bottom',
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                                display: true,
                                labelString: 'Readings'
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                                display: true,
                                labelString: 'Reading ( °C )'
                        }
                    }]
                },
                annotation: {
                  annotations: [
                    {
                      type: "line",
                      mode: "vertical",
                      scaleID: "x-axis-0",
                      borderColor: "red",
                      label: {
                        content: "",
                        enabled: true,
                        position: "top"
                      }
                    }
                  ]
                }
        });
    };

如果您將它與 Chartkick gem 一起使用,下面是一個讓它在 Rails 視圖中工作的示例:

<%=
  line_chart profit_per_day_chart_path(staff), xtitle: 'Day', ytitle: 'Profit',
    library: {
      annotation: {
        annotations: [
          {
            type: 'line',
            mode: 'horizontal',
            scaleID: 'y-axis-0',
            value: 20,
            label: {
              content: 'My Horizontal Line',
              enabled: true
            }
          }
        ]
      }
    }
%>

確保您首先使用 Chart.js 注冊了 chartjs-plugin-annotation.js 插件:

import ChartAnnotationsPlugin from 'chartjs-plugin-annotation';
Chart.plugins.register(ChartAnnotationsPlugin);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM