d3 - attaching data to an axis for rescaling

2020-03-26 11:57发布

问题:

I want to switch between showing actual values and percentages on a scale. At present the data is imported from a csv file and I process the csv to find the domain for the data and display the chart fine. I can switch to showing percentage because the axis domain becomes 0 to 100, but I want to be able to switch back to the actual data domain without having to reprocess the csv file.

Is it possible to attach the data to the axis so I can retrieve it? Something like this:

     vis.append("g")
                .data([calculated_y_domain, [0, 100]])
                .attr("class", "axis yaxis")
                .attr("transform", "translate("+padding+",0)")
                .call(yAxis);

Or is there a better approach?

There is an example here http://bl.ocks.org/3131368 Which I am in the process of tidying up, but the way I do it will depend on the best approach to switching the axis domain.

回答1:

You could create two axis components which utilize your two scales (percentage and value), and transition between the two axes when you transition your data.

var xAxisValue = d3.svg.axis()
    .scale(valueScale)
    .orient("bottom");
var xAxisPercentage = d3.svg.axis()
    .scale(percentageScale)
    .orient("bottom");

d3.select("svg").append("g")
    .attr("class", "x-axis")
    .call(xAxisValue);

/* More code... */

// At the point you want to switch...
var dur = 1500;
d3.select(".x-axis").transition().duration(dur).call(xAxisPercentage);