Chart.js icon indicating copy to clipboard operation
Chart.js copied to clipboard

Tooltip's x coordinate is off in half the chart

Open SachaG opened this issue 11 years ago • 4 comments

I'm trying to use custom tooltips to display labels next to each line of a graph instead of all together:

https://s3.amazonaws.com/f.cl.ly/items/452c3R1w2X1g220H0x1Y/Screen%20Shot%202015-04-13%20at%2012.33.16%20PM.png

Here's my code:

customTooltips = function(tooltip) {

  var tooltipContainer = $('.chartjs-tooltips');

  if (tooltip) {
    // create a "fake" event that we can pass to getPointsAtEvent
    var e = jQuery.Event( "click" );
    e.clientX = tooltip.x - tooltip.xPadding - tooltip.xOffset;
    e.clientY = tooltip.y;
    e.currentTarget = tooltip.chart.canvas;

    var activePoints = myNewChart.getPointsAtEvent(e);

    activePoints.forEach(function (point, index) {
      var childIndex = index + 1;
      var tooltip = tooltipContainer.find('.tooltip:nth-child('+childIndex+')');
      tooltip.find('.tooltip-label').text(point.datasetLabel);
      tooltip.find('.tooltip-value').text(point.value);
      tooltip.css({
        left: point.x,
        top: point.y,
        opacity: 1
      });
    });
  }
};

I'm creating a fake event just so I can use getPointsAtEvent. Not sure if there's a better way? Ideally the tooltip argument passed to the custom tooltip function would just contain the coordinates of each point relevant to the tooltip, but since this is not the case this is the best workaround I could find.

Anyway, this part works well enough. But the problem happens in the right half of the chart, where the x coordinate gets completely thrown off:

https://s3.amazonaws.com/f.cl.ly/items/301C1b051l0Z182Y0i05/Screen%20Shot%202015-04-13%20at%2012.36.15%20PM.png

And since the x coordinate is wrong, getPointsAtEvent returns the wrong set of points.

It seems like some kind of mechanism to avoid having the tooltip bump into the edge of the screen is kicking in. But I can't figure out how to turn it off, or even where in the code that calculation takes place (so that I can offset it in my tooltip's custom code).

So to sum up my question, I'm looking for a way to do either one of these things:

  • Achieve the same result without using getPointsAtEvent at all.
  • Disable the tooltip's auto-offsetting.
  • Figure out how that offsetting is caculated so that I can un-offset it myself.

Thanks for the great library by the way!

SachaG avatar Apr 13 '15 03:04 SachaG

I guess another workaround would be to just superimpose 4 different charts on top of one another. That seems less elegant, but it would also let me tweak each y-axis, so maybe it's a better solution?

SachaG avatar Apr 13 '15 03:04 SachaG

Any idea?

SachaG avatar May 21 '15 01:05 SachaG

there is an open issue on the tooltip.x error #974

ModuLIZER avatar Jun 03 '15 19:06 ModuLIZER

Duplicate of #974

etimberg avatar Dec 25 '15 03:12 etimberg