moarCoffee
moarCoffee

Reputation: 1319

D3 X-value mouseover - function returns NaN

So I am trying to adapt M Bostock's x-value mouseover example to my own graph, the main difference being that I have multiple series instead of his one. For the moment I'm just trying to get the circles to work. My problem is that when I mouseover the graph (in Firebug) I get the message: Unexpected value translate(<my_x>, NaN) parsing transform attribute. I've tried several different ways to fix it but I get the same response each time. What am I doing wrong?

I have a jsFiddle, and the issue is at the bottom:

var focus = main.append('g')
    .attr('class', 'focus')
    .style('display', 'none');

var circles = focus.selectAll('circle')
    .data(sets) // sets = [{name: ..., values:[{date:..., value:...}, ]}, ]
    .enter()
    .append('circle')
    .attr('class', 'circle')
    .attr('r', 4)
    .attr('stroke', function (d) {return colour(d.name);});

main.append('rect')
    .attr('class', 'overlay')
    .attr('width', w)
    .attr('height', h)
    .on('mouseover', function () {focus.style('dispaly', null);})
    .on('mouseout', function () {focus.style('display', 'none');})
    .on('mousemove', mousemove);

function mousemove() {
    var x0 = x_main.invert(d3.mouse(this)[0]),
        i = bisectDate(dataset, x0, 1),
        d0 = dataset[i - 1].date,
        d1 = dataset[i].date,
        c = x0 - d0 > d1 - x0 ? [d1, i] : [d0, i - 1];

    circles.attr('transform', 'translate(' + 
        x_main(c[0]) + ',' + 
        y_main(function (d) {return d.values[c[1]].value;}) + ')'
    );

== EDIT ==

Working jsFiddle

Upvotes: 0

Views: 639

Answers (1)

Scott Cameron
Scott Cameron

Reputation: 5323

You're passing in a function definition into your y_main scale:

circles.attr('transform', 'translate(' + 
    x_main(c[0]) + ',' + 
    y_main(function (d) {return d.values[c[1]].value;}) + ')'
);

selection.attr can take a string value or a callback function but this is trying mixing both of those. You're passing in a string and as the string is constructed it tries to scale the function itself as a value, which will return NaN.

The function version should look like this (returning the entire transform value):

circles.attr('transform', function(d) {
    return 'translate(' + 
        x_main(c[0]) + ',' + 
        y_main(d.values[c[1]].value) + ')';
});

Upvotes: 1

Related Questions