向现有图表Chart.js添加趋势线 [英] Adding trendlines to existing chart Chart.js

查看:361
本文介绍了向现有图表Chart.js添加趋势线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从几个小时以来,我一直在寻找一种向使用Chart.js构建的现有图表中添加趋势线的解决方案

from hours I've been looking for a solution to add trendlines to an existing chart built with Chart.js

我认为我们只能在Chart.js上添加对数趋势线?

I think we can only add logarithmic trendline on Chart.js ?

我不想从头开始绘制趋势线,而是根据这两条线的现有数据添加2条趋势线;请参见此小提琴示例:

I don't want to draw a trendline from scratch, but add 2 trendlines based on existing data of these 2 lines ; please see this fiddle example :

THANK YOU https://jsfiddle.net/blueagency/p88mx3nw/

在此先感谢您的帮助.

推荐答案

当前,chart.js根本没有趋势线功能(甚至没有对数功能).也许您在公共秤配置部分?

Currently, chart.js does not have a trendline capability at all (not even logarithmic). Perhaps you were getting confused with the custom tick format example at the end of the Common Scale Configuration section?

不过,您可以使用 chartjs-plugin-annotation 插件在其上绘制趋势线您的图表,但请记住,您必须实现自己的逻辑以计算直线的正确位置(然后仅使用注释插件进行实际绘制).

You could however use the chartjs-plugin-annotation plugin to draw a trendline on your chart, but keep in mind that you would have to implement your own logic to calculate the correct location of the line (and then just use the annotation plugin to actually draw it).

这里是一个演示如何使用插件的示例(该插件提供了一组annotation属性,您可以将它们添加到图表options中.然后,您只需要创建一个计算趋势线并使用的函数即可.设置注释valueendValue属性的结果.

Here is an example demonstrating how to use the plugin (the plugin provides a set of annotation properties that you can add to your charts options. You would then just need to create a function that calculates the trendline and use the result to set the annotation value and endValue properties.

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1],
    datasets: [{
      label: 'Dataset 1',
      borderColor: window.chartColors.blue,
      borderWidth: 2,
      fill: false,
      data: [19304,13433,9341,6931,5169, 3885,2927,2159,1853,1502, 1176,911,724,590,491, 400,335,280,239,200]
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js Drsw Line on Chart'
    },
    tooltips: {
      mode: 'index',
      intersect: true
    },
    annotation: {
      annotations: [{
        type: 'line',
        mode: 'horizontal',
        scaleID: 'y-axis-0',
        value: 2225,
        endValue: 0,
        borderColor: 'rgb(75, 192, 192)',
        borderWidth: 4,
        label: {
          enabled: true,
          content: 'Trendline',
          yAdjust: -16,
        }
      }]
    }
  }
});

您可以在 codepen 上查看它的运行情况.

You can see it in action at this codepen.

这篇关于向现有图表Chart.js添加趋势线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆