<!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>
依照教程绘制了一个柱形图,效果如图。