Question

I'm trying to show the year on the X axis for the current point I am mousing over on my chart. similar to how it is here: http://www.nytimes.com/interactive/2012/11/30/us/tax-burden.html?_r=0

Here is what I'm working on: jsfiddle.net/Rlightner/u3H8h/

I have set the X axis display to none: to hide the whole x axis initially, (canvasMarket is the variable for my svg):

var xAxisDisplay = canvasMarket.append("g")
      .attr("class", "xaxis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
      .style("display", "none");

Then I've also appended a rectangle (with "fill": "none" and "pointer-events": "all" as the "overlay" class) to canvasMarket with mouseover, mousemove, and mouseout methods, each calling a respective a function:

canvasMarket.append("rect")
      .attr("class", "overlay")
      .attr("transform", "translate("+-tickPadding+",0)")
      .attr("width", width+(tickPadding*2))
      .attr("height", height)
      .on("mouseover", mouseover).on("mouseout", mouseout).on("mousemove", mousemove);

I've also created a mousemove function thate gets the value (d) closest to the mouse, I was trying to use d to reveal the current X value... by using something like xScale(d.date) to select the current X axis date

bisectDate = d3.bisector(function(d) { return d.date; }).left,

function mousemove() {
    var x0 = xScale.invert(d3.mouse(this)[0]),
        i = bisectDate(data, x0, 1),
        d0 = data[i - 1],
        d1 = data[i],
        d = x0 - d0 > d1 - x0 ? d1 : d0;} 

thanks in advance for help!

Was it helpful?

Solution

To do this, you can use the tickValues() function of the axis which allows you to specify tick values explicitly. You would pass in the value you want to show as the only one, although you may want to show the extreme values as well to give some perspective.

The code would look something like this.

function mousemove() {
  var x0 = xScale.invert(d3.mouse(this)[0]),
       i = bisectDate(data, x0, 1),
      d0 = data[i - 1],
      d1 = data[i],
       d = x0 - d0 > d1 - x0 ? d1 : d0;

  xAxis.tickValues([min,d,max]);
  canvasMarket.select("g.xaxis").call(xAxis);
}

OTHER TIPS

Unable to comment.

Hope this helps - HTML Overlay with pageX / pageY

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top