dc.js - display mouseover values from chart outside graph
Asked Answered
W

1

6

I'm looking to create a stacked line graph similar to the following example:

https://dc-js.github.io/dc.js/

However, in addition I would like a field above the graph that displays the current value of the mouseover.

I.e. instead of having to pause for a second with the cursor on the graph, and then having a mouse over box come up, I would like the values to show outside the graph, similar to the way that they do in Google Finance (see how price and vol on top left of graph change as you mouseover). E.g.https://www.google.com/finance?q=apple&ei=MUiWVtnQIdaP0ASy-6Uo

I would really appreciate any info the community could share on what is the best way to approach this.

Wakerife answered 13/1, 2016 at 12:56 Comment(0)
C
9

You can do this by adding your own mouseover/mouseout events to the dots in the chart. I've added a .display-qux span inside the chart div:

<div id="monthly-move-chart">
    ...
    <span class="display-qux"></span>
</div>

but of course it could be somewhere else, this just makes it easy to select for this example.

Then add mouse events using the renderlet event, which is fired after every render and every redraw:

    .on('renderlet', function(chart) {
        chart.selectAll('circle.dot')
            .on('mouseover.foo', function(d) {
                chart.select('.display-qux').text(dateFormat(d.data.key) + ': ' + d.data.value);
            })
            .on('mouseout.foo', function(d) {
                chart.select('.display-qux').text('');
            });
    });

The .foo is an event namespace, to avoid interfering with internal use of these events. You should probably use a word here that is relevant to what you're trying to do. Documentation on event namespaces is here.

Sample output:

external display of current point

The process is the same for adding events to the other charts, but for example, you would selectAll('rect.bar', ... for bar charts, etc.

Clyte answered 14/1, 2016 at 19:41 Comment(2)
Thank you so much Gordon! Exactly what I was looking for! I just wanted to clarify what you mean by 'The .foo is an event namespace, to avoid interfering with internal use of these events'. So what you're saying - and please correct me if I've got this mixed up as I'm new to this - is that essentially .foo is arbitrary label that you've used to avoid the possibility that the 'display' class could already be taken...i.e. just an arbitrary word to make sure that we're accessing a specific element with a unique class assigned to it? is that right?Wakerife
It's an arbitrary label to make sure that our event handlers don't replace any others. The event namespace has nothing to do with the class used to locate the span we're updating - I'll edit my answer to reflect that.Clyte

© 2022 - 2024 — McMap. All rights reserved.