How to set x axis value as tooltip in flot charts textual data

怎甘沉沦 提交于 2019-12-01 13:37:56

The easiest way to solve your problem is to replace the content string with a callback:

tooltipOpts : {
        content : getTooltip,
        defaultTheme : false
      },

I defined getTooltip to get your desired output:

function getTooltip(label, x, y) {
    return "Your sales for " + x + " was $" + y; 
}

It works, as you can see in the updated jsFiddle, but you may want to consider the advice of captain, in comments, and see what's best in your case.

The solution is using tooltipOpts -> content method with a callback function to properly return dynamic data to the label.

I figured out that passing a 4th argument to the callback function of the "tooltipOpts" actually gives you the whole data object from which the chart/graph is constructed from. From here, you can easily extract the X axis labels, using the second argument of this same function as the index of the label to extract.

EXAMPLE:

Data object I'm passing to the plot function:

[
    {
        data: [[1,47478],[2,24500],[3,40177],[4,10512],[5,10512],[6,10512],[7,43439]],
        points: { show: true, radius: 3},
        splines: { show: true, tension: 0.45, lineWidth: 0, fill: 0.4}
    }
],
{
    colors: ['#0cc2aa'],
    series: { shadowSize: 3 },
    xaxis: {
        show: true,
        font: { color: '#ccc' },
        position: 'bottom',
        ticks: [[1,'Thursday'],[2,'Friday'],[3,'Saturday'],[4,'Sunday'],[5,'Monday'],[6,'Tuesday'],[7,'Wednesday']],
    },
    yaxis:{ show: true, font: { color: '#ccc' }, min:1},
    grid: { hoverable: true, clickable: true, borderWidth: 0, color: 'rgba(120,120,120,0.5)' },
    tooltip: true,
    tooltipOpts: {
        content: function(data, x, y, dataObject) {
            var XdataIndex = dataObject.dataIndex;
            var XdataLabel = dataObject.series.xaxis.ticks[XdataIndex].label;
            return y + ' impressions for all of your posts on ' + XdataLabel;
        },
        defaultTheme: false,
        shifts: { x: 0, y: -40 }
    }
}

Chart rendered from the above data object:

As you can see on the image preview, the logic used to render the label's content dynamically form the actual data is this:

tooltipOpts: {
    content: function(data, x, y, dataObject) {
        var XdataIndex = dataObject.dataIndex;
        var XdataLabel = dataObject.series.xaxis.ticks[XdataIndex].label;
        return y + ' impressions for all of your posts on ' + XdataLabel;
    },
    defaultTheme: false,
    shifts: { x: 0, y: -40 }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!