2016-09-06 60 views

回答

0

我的CSS是缺少一個類名稱,我用來識別單個酒吧。我只是給所有酒吧添加了一個「id」屬性,然後通過它來收集它們。

barChart.selectAll("#bar") 
    .data(data) 
    .enter().append("rect") 
    .attr("id", "bar") 
    .attr("fill", "grey") 
    .attr("x", function (d) { return x(d.name); }) 
    .attr("width", x.rangeBand()) 
    .attr("y", function (d) { return y(d.value); }) 
    .attr("height", function (d) { return height - y(d.value); }) 
    .on("click", function() {sortBars();}) 
    .on("mouseover", function(d){ 

     var delta = d.value; 
     var xPos = parseFloat(d3.select(this).attr("x")); 
     var yPos = parseFloat(d3.select(this).attr("y")); 
     var height = parseFloat(d3.select(this).attr("height")); 
     var width = parseFloat(d3.select(this).attr("width")); 

     d3.select(this).attr("fill", "orange"); 

     barChart.append("text") 
     .attr("x", xPos) 
     .attr("y", yPos - 3) 
     .attr("font-family", "sans-serif") 
     .attr("font-size", "10px") 
     .attr("font-weight", "bold") 
     .attr("fill", "black") 
     .attr("text-anchor", "middle") 
     .attr("id", "tooltip") 
     .attr("transform", "translate(" + width/2 + ")") 
     .text(d.name +": "+ d.value); 
     }) 
    .on("mouseout", function(){ 
      barChart.select("#tooltip").remove(); 
      d3.select(this).attr("fill", "grey"); 

    }); 

var sortOrder = true; 

var sortBars = function() { 

      //Flip value of sortOrder 
      sortOrder = !sortOrder; 

      var x0 = x.domain(data.sort(sortOrder ? function(a, b) { return b.value - a.value; } 
       : function(a, b) { return d3.ascending(a.name, b.name); }) 
       .map(function(d) { return d.name; })) 
       .copy(); 

      barChart.selectAll("#bar") 
       .sort(function(a, b) { return x0(a.name) - x0(b.name); }); 

      var transition = barChart.transition().duration(750), 
       delay = function(d, i) { return i * 50; }; 

       transition.selectAll("#bar") 
        .delay(delay) 
        .attr("x", function(d) { return x0(d.name); }); 

       transition.select(".x.axis") 
        .call(xAxis) 
        .selectAll("g") 
        .delay(delay); 
}; 

function type(d) { 
    d.value = +d.value; 
    return d; 
}