问题
I am trying to take Mike Bostock's Sortable Bar Chart code and convert it to a horizontal bar chart. https://bl.ocks.org/mbostock/3885705
My bar chart appears just fine but the console gives this error message whenever the input is clicked:
Uncaught ReferenceError: data is not defined
at HTMLInputElement.change (test3.html:168)
at pt.each (d3.v4.min.js:2)
at test3.html:161
I have a feeling this is related to my using v4 of d3 rather than v3 but I'm not really sure.
Here's the whole script:
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("#graphlocation").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
;
var x = d3.scaleLinear()
.range([0, width]);
var y = d3.scaleBand()
.range([height, 0]);
var xAxis = d3.axisBottom(x)
.ticks(10);
var yAxis = d3.axisLeft(y);
d3.tsv("15.tsv", type, function(error, data) {
if (error) throw error;
x.domain([0, d3.max(data, function(d) { return d.value; })]);
y.domain(data.map(function(d) { return d.datesort; }))
.paddingInner(0.1)
.paddingOuter(0.5);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("transform", "translate(" + width + ",0)")
.attr("y", -5)
.style("text-anchor", "end")
.text("Frequency");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("height", y.bandwidth())
.attr("y", function(d) { return y(d.datesort); })
.attr("width", function(d) { return x(d.value); });
});
function type(d) {
d.frequency = +d.frequency;
return d;
}
d3.select("input").on("change", change);
var sortTimeout = setTimeout(function() {
d3.select("input").property("checked", true).each(change);
}, 2000);
function change() {
clearTimeout(sortTimeout);
// Copy-on-write since tweens are evaluated after a delay.
var y0 = y.domain(data.sort(this.checked
? function(a, b) { return b.datesort - a.datesort; }
: function(a, b) { return d3.ascending(a.value, b.value); })
.map(function(d) { return d.value; }))
.copy();
svg.selectAll(".bar")
.sort(function(a, b) { return y0(a.value) - y0(b.value); });
var transition = svg.transition().duration(750),
delay = function(d, i) { return i * 50; };
transition.selectAll(".bar")
.delay(delay)
.attr("y", function(d) { return y0(d.value); });
transition.select(".y.axis")
.call(yAxis)
.selectAll("g")
.delay(delay);
}
Line 168 is var y0 = y.domain(data.sort(this.checked
and line 161 is d3.select("input").property("checked", true).each(change);
Thanks for any help you can provide.
来源:https://stackoverflow.com/questions/47372679/sortable-bar-chart-in-d3-v4