0

I have a simple Chart.js line chart, which shows the costs of two decisions. I now want to show the break even of one over the other, which is basically the intersection.

I made an example of what I have so far 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);

How can I

  1. Show a tooltip at the interception of the two lines
  2. Show the values for the interception (inside a tooltip or at the axis)
  3. Move the legend inside the chart

Any help would be appreciated. Thank you.

lony
  • 6,733
  • 11
  • 60
  • 92
  • 1
    Possible duplicate of [Intersection point in line graph in Chart.js?](http://stackoverflow.com/questions/42621329/intersection-point-in-line-graph-in-chart-js) – Deep 3015 Apr 30 '17 at 12:27
  • Nice that helped, even I thought it may be easier. Thank you. – lony May 01 '17 at 09:18

1 Answers1

0

This is very specific to the problem

 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/

Rhea
  • 644
  • 1
  • 5
  • 14
  • Thanks not exactly what I wanted as my values are dynamic but thank you for the idea. – lony May 01 '17 at 09:18
  • 1
    you can pass the values of x1,x2,y1,y2,y3,y4, to the function from your dyanamic list – Rhea May 01 '17 at 21:07