用d3来生成一个建议的条形图这里将这个方法封装到一个函数中dataShow(data)方法:
function dataShow(data) { document.getElementById('container').innerHTML = ""; var margin = { top : 20, right : 20, bottom : 30, left : 40 }, width = 930 - margin.left - margin.right, height = 200 - margin.top - margin.bottom; var x = d3.scale.ordinal().rangeRoundBands([ 0, width ], .1, 1); var y = d3.scale.linear().range([ height, 0 ]); var xAxis = d3.svg.axis().scale(x).orient("bottom"); var yAxis = d3.svg.axis().scale(y).orient("left"); var svg = d3.select("#container").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 + ")"); x.domain(data.map(function(d) { return d.name; })); y.domain([ 0, d3.max(data, function(d) { return d.value; }) ]); svg.append("g").attr("class", "x axis").attr("transform", "translate(0," + height + ")").call(xAxis); svg.append("g").attr("class", "y axis").call(yAxis).append("text") .attr("transform", "rotate(-90)").attr("y", 6).attr("dy", ".71em").style("text-anchor", "end").text("工作时间"); svg.selectAll(".bar").data(data).enter().append("rect").attr("class", "bar").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); }).attr("fill", function(d) { return "rgb(255, 193, " + (d.value * 10) + ")"; }).on( "mouseover", function(d) { var xPosition = parseFloat(d3.select(this).attr("x")) + x.rangeBand() / 2; var yPosition = parseFloat(d3.select(this).attr("y")) / 2 + height / 2; //Update the tooltip position and value d3.select("#tooltip").style("left", xPosition + "px") .style("top", yPosition + "px").select("#value") .text(d.value); //Show the tooltip d3.select("#tooltip").classed("hidden", false); }).on("mouseout", function(d) { d3.select("#tooltip").classed("hidden", true); }); d3.select("input").on("change", change); var sortTimeout = setTimeout(function() { d3.select("#sort").property("checked", true).each(change); }, 2000); function change() { clearTimeout(sortTimeout); // Copy-on-write since tweens are evaluated after a delay. var x0 = x.domain(data.sort(this.checked ? 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(); var transition = svg.transition().duration(750), delay = function( d, i) { return i * 100; }; transition.selectAll(".bar").delay(delay).attr("x", function(d) { return x0(d.name); }); transition.select(".x.axis").call(xAxis).selectAll("g") .delay(delay); } ; };