Javascript 在 v2 上的 chart.js 中的图表上绘制水平线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42691873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:22:14  来源:igfitidea点击:

Draw horizontal line on chart in chart.js on v2

javascriptjquerychartschart.js

提问by tech_geek

I have drawn a line chart using chart.js. For the labels and datasets i am getting values from the database. I am new to chart.js and its very powerful library, yet i am unable to completely understand it. I want to draw multiples horizontal lines. Like where if mean of dataset, standard deviation and min and max. I have tried the question here in stackoverflow but these are giving errors or may be i am not able to understand the working. This is my chart.js code

我使用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
});}

回答by jordanwillis

You could use the chart.js annotation pluginto easily draw lines on your chart without having to mess with rendering pixels in your canvas manually (the old approach that is giving you errors). Note, the plugin is created/supported by the same team as chart.js and is mentioned in the chart.js docs.

您可以使用chart.js 注释插件轻松地在图表上绘制线条,而无需手动在画布中渲染像素(旧方法会给您带来错误)。请注意,该插件由与 chart.js 相同的团队创建/支持,并在chart.js 文档中提及。

Here is an example codependemonstrating creating a line on a chart.

这是一个示例代码笔,演示在图表上创建一条线。

Once you add the plugin, you simply just set annotationproperties in your chart config. Here is an example.

添加插件后,您只需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'
        }
      }]
    }
  }
});

回答by safeer sathar

if you want to draw threshold line,easiest way is that using mixed line chart.

如果要绘制阈值线,最简单的方法是使用混合折线图。

Note: Make an array filled with threshold value and the length should be same as your dataset.

注意:制作一个填充阈值的数组,长度应与您的数据集相同。

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"
                      }
                    }
                  ]
                }
        });
    };

回答by FireEmerald

If you are using the NPMpackage chartjs-plugin-annotation.js, the important thing - which you may forget, is to registerthe plugin.

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

So first of all you installed the npm packages (here for React):

所以首先你安装了 npm 包(这里是React):

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

See Vue.jsor Angularfor their framework depending packages.

请参阅Vue.jsAngular以了解其依赖于框架的包。

Option 1: Global plugin registration

选项 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} />
    )
}

Option 2: Per chart plugin registration

选项 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]} />
    )
}

chartDatais equivalent to the data: {section and chartOptsto options: {from jordanwillis answer. See thisgithub post for further information.

chartData相当于data: {部分和chartOptsto options: {from jordanwillis answer。有关更多信息,请参阅github 帖子。

There are many other plugins availablefor chart.js.

chart.js还有许多其他插件可用

回答by stwr667

Here's an example of getting it working in a Rails view if you're using it with the Chartkick gem:

如果您将它与 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
            }
          }
        ]
      }
    }
%>

Ensure that you've registered the chartjs-plugin-annotation.js plugin with Chart.js first:

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

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