简体   繁体   中英

JavaScript - Chart.js tooltip shows wrong x-axis value

I have a chart with two different datasets, but sometimes they have the same x, y coordinates. But when I hover a shared point , it sometimes shows the wrong date. The y value is correct, but it's the x value that is not showing correctly.

Try hovering a shared point here on codepen .

In the image below you can see I'm hovering { y: 56.04, x: April 05, 2014 } , but is shows the xLabel value of 58.28 , which is April 15, 2012 . Also, you can see in the chart that both 57.05 and 58.28 have April 15, 2012 as x-value, but they are not on the same y position!

The code is too long to share on stackoverflow, but I made this codepen so you can view, fork and edit it there.

工具提示错误


Update

I updated the pen and fixed points that have the same date. I also added type: 'time' thanks to @Oluwafemi Sule .

Here my edited pen .

But now, the dates on the x-axis are weird. They don't say March 06, 2011 anymore, but they say Q1 2011 . And the tooltips still bug.

I solved my problem by using tooltip callback like this:

options: {
    tooltips: {
        callbacks: {
            title: function(tooltipItems, data) {
                return data.datasets[tooltipItems[0].datasetIndex].data[tooltipItems[0].index].x;
            }
        }
    }
}

Now my tooltips getting their title directly from the corresponding dataset .

Chartjs Version: 2.9.3

You defined a custom scale for a category cartesian axis in your chart configuration. Set the type for your xAxes to 'category'. This may not be neccessary as ChartJS picks this up by default.

options: {
    scales: {
        xAxes: [{
            type: 'category',
            ....

Also, the second data set isn't formatted properly . You should supply the data points in {x: xval, y: yval} format.

References:

http://www.chartjs.org/docs/latest/axes/cartesian/time.html#time-cartesian-axis

I belive that you need pass the labels.

labels: ["09:00", "09:30", "09:50", "10:10", "10:30", "10:50", "11:10"],

//////////////////////////////////////////////

var chartPluginLineaHorizontal = {
        afterDraw: function (chartobj, chartobjDos) {
            if (chartobj.options.lineaHorizontal) {
                var ctx = chartobj.chart.ctx;
                var valorY = chartobj.scales["y-axis-0"].getPixelForValue(chartobj.options.lineaHorizontal);
                ctx.beginPath();
                ctx.moveTo(0, valorY);
                ctx.lineTo(chartobj.chart.width, valorY);
                ctx.strokeStyle = "red";
                ctx.stroke();

            }
        }
    }
    Chart.pluginService.register(chartPluginLineaHorizontal);

    var chartPluginLineaHorizontalDos = {
        afterDraw: function (chartobj) {
            if (chartobj.options.lineaHorizontal) {
                var ctx = chartobj.chart.ctx;
                var valorY = chartobj.scales["y-axis-0"].getPixelForValue(chartobj.options.lineaHorizontalDos);
                ctx.beginPath();
                ctx.moveTo(0, valorY);
                ctx.lineTo(chartobj.chart.width, valorY);
                ctx.strokeStyle = "red";
                ctx.stroke();
            }
        }
    }
    Chart.pluginService.register(chartPluginLineaHorizontalDos);

    // Define a plugin to provide data labels
    Chart.plugins.register({
        afterDatasetsDraw: function (chartobj) {
            var ctx = chartobj.chart.ctx;

            chartobj.data.datasets.forEach(function (dataset, i) {
                //debugger
                var meta = chartobj.getDatasetMeta(i);
                if (!meta.hidden) {
                    meta.data.forEach(function (element, index) {
                        // Draw the text in black, with the specified font
                        ctx.fillStyle = 'rgb(0, 0, 0)';

                        var fontSize = 16;
                        var fontStyle = 'inherit';
                        var fontFamily = 'sans-serif';
                        ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);

                        // Just naively convert to string for now
                        var dataString = dataset.data[index].y.toString();

                        // Make sure alignment settings are correct
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';

                        var padding = 5;
                        var position = element.tooltipPosition();
                        ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                    });
                }
            });
        }
    });

                var ctx = document.getElementById('myChart').getContext('2d');
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: ["09:00", "09:30", "09:50", "10:10", "10:30", "10:50", "11:10"],
                        datasets: [{
                            label: "My First dataset",
                            data: [
                                    {
                                        x: "09:30",
                                        y: 127
                                    },
                                   {
                                       x: "09:30",
                                       y: 140
                                   },
                                   {
                                       x: "09:50",
                                       y: 135
                                   },
                                   {
                                       x: "10:10",
                                       y: 122
                                   }, {
                                       x: "10:30",
                                       y: 135
                                   }, {
                                       x: "10:50",
                                       y: 135
                                   }],
                            backgroundColor: "rgba(0,255,51,0.5)",
                                        borderColor: "rgba(0,255,51,0.5)",
                                        fill: false
                        },
                                {
                                    label: "My second dataset",
                                    data: [
                                        {
                                            x: "09:50",
                                            y: 95
                                        },
                                   {
                                       x: "10:10",
                                       y: 140
                                   },
                                   {
                                       x: "10:30",
                                       y: 130
                                   },
                                   {
                                       x: "10:50", 
                                       y: 150
                                   },
                                   {
                                       x: "11:10",
                                       y: 143
                                   }],
                                                backgroundColor: "rgba(0,98,31,0.5)",
                                                borderColor: "rgba(0,98,31,0.5)",
                                                fill: false
                                }]
                    },
                    options: {
                        lineaHorizontal: 140,
                        lineaHorizontalDos: 100,
                        elements: {
                            line: {
                                tension: 0
                            }
                        }

                    }


                })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM