Morris graphs. Have custom tooltip when hover

2019-01-18 05:03发布

问题:

I am using morris.js (which has a dependency on raphael) for creating stacked bar graphs. For each stacked bar I want to show the split for the various levels in the bar as a tooltip. I tried using the hoverCallback: but it doesn't seem to give me control over the particular element I am hovering over. I only get the content for that particular bar.

I have setup a JSBIN example for the same here:

When you hover over the bar it shows the index of the bar at the bottom. I want to show the content as a tool tip instead.JSBIN example

回答1:

Piece of cake. Demo and code:

<script type="text/javascript">
Morris.Bar({
    element: 'bar-example',
    data: [
        {y: '2006',a: 100,b: 90}, 
        {y: '2007',a: 75,b: 65}, 
        {y: '2008',a: 50,b: 40}, 
        {y: '2009',a: 75,b: 65}, 
        {y: '2010',a: 50,b: 40}, 
        {y: '2011',a: 75,b: 65}, 
        {y: '2012',a: 100,b: 90}
    ],
    hoverCallback: function(index, options, content) {
        return(content);
    },
    xkey: 'y',
    ykeys: ['a', 'b'],
    stacked: true,
    labels: ['Series A', 'Series B'] // rename it for the 'onhover' caption change
});
</script>

UPD:

For flying label, you need to add Morris CSS stylesheet to the code - demo

IMPORTANT NOTE

Flying labels works since version 0.4.3



回答2:

http://jsbin.com/finuqazofe/1/edit?html,js,output

{ y: ..., x: ..., label: "my own label"},'

...
Morris.Line({
    hoverCallback: function(index, options, content) {
        var data = options.data[index];
        $(".morris-hover").html('<div>Custom label: ' + data.label + '</div>');
    },
    ...
    other params
});