Chart.js在轴的交点处添加工具提示(收支平衡)

时间:2017-04-30 12:16:13

标签: javascript jquery charts chart.js

我有一个简单的Chart.js折线图,它显示了两个决策的成本。我现在想要显示一个在另一个上方的收支平衡,这基本上就是交叉点。

我举了一个例子,说明了我到目前为止here

var ctx = document.getElementById("chart");
var options = {
    type: 'line',
    data: {
        labels: ["1", "2", "4", "6", "7", "10"],
        datasets: [
            {
                backgroundColor: "rgba(151,187,205,0.2)",
                borderColor: "rgba(151,187,205,1)",
                data: [80, 80, 80, 80, 80, 80]
            },
            {
                backgroundColor: "rgba(220,220,220,0.2)",
                borderColor: "rgba(220,220,220,1)",
                data: [8.84, 17.68, 35.36, 53.04, 70.72, 88.4]
            }
        ]
    },
    options: {
        tooltips: {
            enabled: false
        },
        legend: {
            position: 'top'
        }            
    }
};
var myChart = new Chart(ctx, options);

我怎么能

  1. 在截取两行时显示工具提示
  2. 显示拦截的值(在工具提示内或轴上)
  3. 在图表中移动图例
  4. 任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

非常具体问题

 Chart.plugins.register({
afterInit: function(chart) {
var intersect = getIntersection();
 var datasets = chart.data.datasets;
 var labels = chart.data.labels;
 labels.push(intersect.x)
    labels.sort(function(a,b){return a - b});
y = labels.indexOf(intersect.x);
chart.data.datasets.forEach(function(ds,i){ds.data.splice(y, 0, intersect.y)});

 }
 })
 function getIntersection(){
  var y2=17.68, y1=8.84,x2=2,x1=1,x3 = x1, x4 = x2,
      y4=80,y3=80;
  var x=((x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1-y2)*(x3-x4));
var y=((x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1-y2)*(x3-x4));
    x = Math.round(x*100)/100;
y = Math.round(y*100)/100;
return {x:x,y:y}  ;

http://jsfiddle.net/o3cyhxrn/4/