D3.js 更自由的条形图
一、添加一个矩形
//Width and height var w = 500; var h = 100; 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", 0) .attr("y", 0) .attr("width", 20) .attr("height", 100);
二、添加多条矩形
//Width and height var w = 500; var h = 100; 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 * 21; //Bar width of 20 plus 1 for padding }) .attr("y", 0) .attr("width", 20) .attr("height", 100);
三、均匀的添加条-定条宽
除的方式(i * (w / dataset.length);)作为条和间隙的总宽度,在设置固定宽度小于总宽度,这时就会自然生成一个空白间隙
一句话:条的宽度固定,总宽-条宽=空白宽。空白宽取决于总宽,总宽取决于计算表达式(w / dataset.length)
//Width and height 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", 0) .attr("width", 20) .attr("height", 100);
四、均匀的添加条-定间隙宽
一句话:间隙的宽度固定,总宽-空白宽=条宽。条宽取决于总宽(w / dataset.length - barPadding),总宽取决于计算表达式(w / dataset.length)
//Width and height 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 ]; //Create SVG element 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", 0) .attr("width", w / dataset.length - barPadding) .attr("height", 100);