日期:2014-05-16  浏览次数:20376 次

【D3.V3.js系列教程】--(五)用层画条形图

【D3.V3.js系列教程】--(五)用层画条形图

1、为同类层添加样式

div.bar {
    display: inline-block;
    width: 20px;
    height: 75px;   /* We'll override this later */
    background-color: teal;
}

2、声明要为某类层设置属性

.attr("class", "bar")

3、为每个特定的层设置属性

.style("height", function(d) {
    var barHeight = d * 5;  //Scale up by factor of 5
    return barHeight + "px";
});

4、设置层之间的间隔

margin-right: 2px;

5、源码

<!DOCTYPE html>
<html>
  <head>
		<meta charset="utf-8">
		<title>testD3-3-drawingDivBar</title>
		<script type="text/javascript" src="http://localhost:8080/spring/js/d3.v3.js"></script>
	<style type="text/css">
		
			div.bar {
				display: inline-block;
				width: 20px;
				height: 75px;	/* Gets overriden by D3-assigned height below */
				margin-right: 2px;
				background-color: teal;
			}
		
		</style>
	</head>
	<body>
		<script type="text/javascript">
		
			var dataset = [ 5, 10, 15, 20, 25 ];
			
			d3.select("body").selectAll("div")
				.data(dataset)
				.enter()
				.append("div")
				.attr("class", "bar")
				.style("height", function(d) {
					var barHeight = d * 5;
					return barHeight + "px";
				});
			
		</script>
	</body>
</html>


 

6、效果