0
我用簡單的.csv數據創建了條形圖。第一列是「團隊」,其中團隊名稱包含文本;第二列是「目標」,其中包含進球數。
但是接下來我想對酒吧進行排序,讓更多目標的團隊成爲第一。我嘗試了所有可以在網上找到的東西,但沒有一個適用於我的情況。我感到很困惑......D3條形圖排序不起作用
代碼:
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
svg = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("StatsByClub1.csv", function(d) {
d.Goals = +d.Goals;
return d;
}, function(error, data) {
if (error) throw error;
x.domain(data.map(function(d) { return d.Team; }));
y.domain([0, d3.max(data, function(d) { return d.Goals; })]);
svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Goals");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
// sorting does not work!
.sort(function(a, b) {d3.descending(a.Goals, b.Goals)})
.attr("class", "bar")
.attr("x", function(d) { return x(d.Team); })
.attr("y", function(d) { return y(d.Goals); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.Goals); });
的數據是這樣的:
Team Goals
Man. United 49
Man. City 71
Arsenal 65
Hotspur 69
Liverpool 63
Chelsea 59
Everton 59
Swansea 48
Stoke City 41
Sunderland 42