绘制条形图的输入数只须要一个表示每一个条数据量的数组就行。javascript
var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
var w = 500; var h = 100; var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h);
svg.selectAll("rect") // 选择一组数据,这个时候尚未元素 .data(dataset) // 加载数据集 .enter() // 给新增数据添加占位符,表示将要添加一个元素 .append("rect") //添加矩形元素 // 这里属性的设置后面单说
咱们绘制的思路是:css
条宽 = 条实际宽度 + 间隙的宽度。html
其中条宽 = (w / dataset.length)java
间隙的宽度 = barPaddingspring
条高 = 条长-纵坐标(纵坐标是从上到下计算,即下方向为正) 即条高 = h - (d * 4)编程
条的颜色用据数据集生成的动态RGB值填充。数组
因此结合上面分析结果就是:app
svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", function(d, i) { return i * (w / dataset.length); }) .attr("y", function(d) { return h - (d * 4); }) .attr("width", w / dataset.length - barPadding) .attr("height", function(d) { return d * 4; }) .attr("fill", function(d) { return "rgb(0, 0, " + (d * 10) + ")"; });
.attr("x", function(d, i) { return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2; })
不少初学者看不懂这里的.attr("x", function(d, i)
,其实看前面的文章你们应该知道,x属性表明矩形的起点位置。这个匿名函数的入参两个d和i,分别表明当前元素绑定的数据值,当前元素的索引(第几个元素)。d和i的名字能够换成其余单词。svg
同理,添加文本并指定文本的XY坐标,其中:函数
x坐标:i * (w / dataset.length) + (w / dataset.length - barPadding) / 2; y坐标:h - (d * 4) + 14;
svg.selectAll("text") .data(dataset) .enter() .append("text") .text(function(d) { return d; }) .attr("text-anchor", "middle") .attr("x", function(d, i) { return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2; }) .attr("y", function(d) { return h - (d * 4) + 14; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") .attr("fill", "white");
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>testD3-8-drawBar.html</title> <script type="text/javascript" src="http://localhost:8080/spring/js/d3.v3.js"></script> <style type="text/css"> </style> </head> <body> <script type="text/javascript"> //SVG高宽 var w = 500; var h = 100; var barPadding = 1; var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13, 11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ]; //建立SVG var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", function(d, i) { return i * (w / dataset.length); }) .attr("y", function(d) { return h - (d * 4); }) .attr("width", w / dataset.length - barPadding) .attr("height", function(d) { return d * 4; }) .attr("fill", function(d) { return "rgb(0, 0, " + (d * 10) + ")"; }); svg.selectAll("text") .data(dataset) .enter() .append("text") .text(function(d) { return d; }) .attr("text-anchor", "middle") .attr("x", function(d, i) { return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2; }) .attr("y", function(d) { return h - (d * 4) + 14; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") .attr("fill", "white"); </script> </body> </html>