JMcClure
JMcClure

Reputation: 711

D3.js - Updating title for svg path

I've a d3 pie chart, and I'm having trouble figuring out how to update some SVG titles which are appended to the individual paths when I update the path values through a selection.

A stripped down version of my code is below.

I've been trying different code snippets, especially in function change(), but haven't found the knack for it yet. I didn't find any good examples already posted, either.

Again, I'm using the path title tags as tooltips and am trying to update their text values as I update the path values.

Any help is so very much appreciated, as I'm on deadline with this project by week's end.

Thanks so much again.

var dataset = {
Y2012:  [1000, 2000, 3000],
Y2011:  [3000, 2000, 1000],
//etc.
};

var width = 300,
    height = 300,
    radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
    .sort(null);

var arc = d3.svg.arc()
    .innerRadius(outer_radius - 85)
    .outerRadius(outer_radius - 50);

var svg = d3.select(".svg_container").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var path = svg.selectAll("path")
    .data(pie(dataset.Y2012))
  .enter().append("path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", outer_arc)
    .each(function(d) { this._current = d; });

var tooltips= d3.selectAll("path")
  .append("title")
    .classed("tooltip", true)
    .text(function(d) { return d.value });

d3.selectAll("#select_year").on("change", change);

function change() {
  path = path.data(pie(dataset[this.value])); // update the data
  path.transition().duration(750).attrTween("d", arcPathTween);
}

function arcPathTween(a) {
  var i = d3.interpolate(this._current, a);
  this._current = i(0);
  return function(t) {
    return arc(i(t));
  };
}

Upvotes: 2

Views: 5950

Answers (1)

The problem is that you don't update the title text in function change(). Even though your title text is created by a function accessing the data, you have to realize that this function doesn't automagically execute again when you update the data. This has to be done manually:

function change(newYear) {
    path = path.data(pie(dataset[newYear])); // update the data
    path.transition().duration(750).attrTween("d", arcPathTween);
    path.select("title").text(function(d) { return d.value });
}

I have also creating a fiddle illustrating the solution.

If you want to avoid duplication of code (which you should), you could use the general update pattern meaning that you do initialization and update in the same function.

Upvotes: 3

Related Questions