d3.js 可视化学习笔记(一)——柱形图

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>

	<script type="text/javascript"></script>
	<script src="http://d3js.org/d3.v3.min.js" charset='utf-8'></script>

	<script type="text/javascript">
		var width = 300;
		var height = 300;

		var dataset = [1.2, 2.3, 0.9, 1.5, 3.3, 1.7, 2.5, 1.3];
		var min = d3.min(dataset);
		var max = d3.max(dataset);
		var padding = {left:30, right:30, top:20, bottom:20};

		

		var svg = d3.select("body")
					.append("svg")
					.attr("width",width)
					.attr("height",height);

		var xScale = d3.scale.ordinal()
						.domain(d3.range(dataset.length))
						.rangeRoundBands([0, width - padding.left - padding.right]);
		var yScale = d3.scale.linear()
						.domain([0, d3.max(dataset)])
						.range([height - padding.top - padding.bottom, 0]);

		var xAxis = d3.svg.axis()
						.scale(xScale)
						.orient("bottom");
		var yAxis = d3.svg.axis() 
						.scale(yScale)
						.orient("left");


		svg.selectAll(".MyRect")
			.data(dataset)
			.enter()
			.append("rect")
			.attr("class","MyRect")
			.attr("transform","translate("+padding.left+","+padding.top + ")")
			.attr("x",function(d,i){
				return xScale(i)+2;
			})
			.attr("y",function(d,i){
				return yScale(d);
			})
			.attr("width",xScale.rangeBand() - 4)
			.attr("height",function(d,i){
				return height-padding.top-padding.bottom-yScale(d);
			})
			.attr("fill","steelblue");

		var texts = svg.selectAll(".MyText")
						.data(dataset)
						.enter()
						.append("text")
						.attr("class","MyText")
						.attr("transform","translate("+padding.left+","+padding.top+")")
						.attr("x",function(d,i){
							return xScale(i)+2;
						})
						.attr("y",function(d){
							return yScale(d);
						})
						.attr("dx",function(){
							return (xScale.rangeBand()-4)/2;
						})
						.attr("dy",20)
						.attr("text-anchor","middle")
						.attr("font-family","sans-serif")
						.attr("font-size",'15px')
						.attr("fill","white")
						.text(function(d){
							return d;
						})

		svg.append("g").attr("class","axis").attr("transform","translate("+padding.left+","+(height-padding.bottom)+")").call(xAxis);
		svg.append("g").attr("class","axis").attr("transform","translate("+padding.left+","+(padding.top)+")").call(yAxis);
	</script>
	<style type="text/css">
		.axis path,
		.axis line{
			fill: none;
			stroke: black;
			shape-rendering: crispEdges;
		}
		.axis text{
			font-family: sans-serif;
			font-size: 11px;
		}
	</style>
</body>
</html>


依照教程绘制了一个柱形图,效果如图。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值