【问题标题】:Draw horizontal line on chart in chart.js on v2在 v2 上的 chart.js 中的图表上绘制水平线
【发布时间】:2017-07-30 05:36:00
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery charts chart.js


    【解决方案1】:

    您可以使用chart.js annotation plugin 在图表上轻松绘制线条,而不必在画布中手动渲染像素(旧方法会导致错误)。请注意,该插件由与 chart.js 相同的团队创建/支持,并在 chart.js docs 中提及。

    这是一个 example codepen 演示在图表上创建一条线。

    添加插件后,您只需在图表配置中设置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'
            }
          }]
        }
      }
    });
    

    【讨论】:

    • 您是否遇到任何错误?你能描述发生了什么吗?这可能是一个简单的 chart.js 版本控制问题。此解决方案针对 chart.js v2.3.0(问题得到解答时的最新版本),但是在最新版本 (v2.7.1) 中一些选项和 API 发生了变化。
    • 现已解决:stackoverflow.com/questions/47655173/…。谢谢乔丹!
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      如果您使用的是 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: { 部分和 chartOptsoptions: { 来自 jordanwillis answer。更多信息请参见thisgithub 帖子。

      chart.js 还有很多其他的plugins available

      【讨论】:

        【解决方案4】:

        如果您将它与 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);
        

        【讨论】:

          猜你喜欢
          • 2015-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多