Question

Is it possible to show the y-axis title horizontally instead of vertically using either d3.js or nvd3.js ? Or is there a mouseover event on label that can be used to show ballon tip with y-axis title horizontally ? Any example will be a great help.

Was it helpful?

Solution

Axis titles are not part of the standard d3 axis, they are added by NVD3. However, like all components, once NVD3 creates them you can use d3 to select and modify them.

NVD3 creates the axis labels with the class nv-axislabel. The y axis group as a whole is given the classes nv-y nv-axis. Therefore, after drawing the graph you can select the y-axis label with

d3.select("g.nv-y.nv-axis").select("text.nv-axislabel")

Once selected, you can change it's positioning however you want. Unfortunately, it's not as simple as removing the rotation, because that throws off the rest of the position -- the x and y positions are applied after the rotation, so remove the rotation and they send the text off screen.

The following code positions the label just above the top of the axis:

d3.select("g.nv-y.nv-axis").select("text.nv-axislabel")
    .attr({"transform":null, x:0, y:"-1em"})
    .style("text-anchor","end");

For your other idea -- draw a horizontal tooltip -- you can take advantage of the browser's default tooltip for any element that contains an SVG <title> element. However, one complication is that NVD3 turns off mouse events on the axis elements, so you would have to turn them back on:

  var yLabel = d3.select("g.nv-y.nv-axis").select("text.nv-axislabel")
      .style("pointer-events", "all");

  yLabel
    .append("title")
    .text( yLabel.text() );

Again, whichever option you choose, you have to do it after drawing the graph. You will also have to re-do the changes after every update, so you should probably group them in a function to make that easier.

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