【d3.js教程02】d3入门
最后更新于:2022-04-01 14:17:57
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-19_57161003d1807.jpg)
~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.axis path,
.axis line{
stroke: black;
fill: none;
shape-rendering: crispedges;
}
</style>
<script src="js/d3.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
/*svg大小*/
var width = 400;
var height = 400;
/*svg周边留白*/
var padding = {left:30,right:30,top:20,bottom:20};
/*在body里面添加一个SVG画布*/
var svg = d3.select("body")
.append("svg")
.attr("width",width)
.attr("height",height);
/*定义一个数据集*/
var dataset = [10,20,30,40,50,60,33,25,12,5];
/*x轴的比例尺*/
var xScale = d3.scale.ordinal() //ordinal是序数的意思 可以理解为序数比例尺 (一组序数来分给定的范围)
.domain(d3.range(dataset.length)) //数据源(range会将数字生成数组)
.rangeRoundBands([0,width-padding.left-padding.right]); //输出结果集
/*y轴的比例尺*/
var yScale = d3.scale.linear() //linear理解为线性比例尺 (一个线性的范围来分给定的范围)
.domain([0,d3.max(dataset)]) //数据源
.range([height-padding.top-padding.bottom,0]); //对应输出的结果集(故意要写反,因为后面这个值是用来减去的)
/*矩形块之间的空白*/
var rectPadding = 4;
/*定义坐标轴*/
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
/*添加矩形元素*/
var rects = 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)+rectPadding/2;
})
.attr("y",function(d){
return yScale(d);
})
.attr("width",xScale.rangeBand()-rectPadding)
.attr("height",function(d){
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)-rectPadding; //设定各自水平位移
})
.attr("y",function(d){
return yScale(d); //设定各自竖直位移
})
.attr("dx",function(){
return (xScale.rangeBand() - rectPadding)/2; //各文字水平位移(这个位移是相对rect位移的)
})
.attr("dy",function(d){
return 20; //各文字竖直位移
})
.text(function(d){
return d; //文本显示
})
.attr("fill","white"); //设置为白色
/*添加坐标轴的元素*/
svg.append("g")
.attr("class","axis")
.attr("transform","translate("+padding.left+","+380+")") //规定坐标轴的位移
.call(xAxis);
svg.append("g")
.attr("class","axis")
.attr("transform","translate("+padding.left+","+padding.top+")")
.call(yAxis);
</script>
</body>
</html>
~~~