D3,github开源,代码由javascript编写,目的是数据可视化
还是慕课网的视频学习的记录。
感谢视频作者 @LuckyYang
1.画布制作
线形图表
步骤:web容器---生成曲线--生成xy轴和标签
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css"/>
</head>
<body>
<div id="container"></div>
<script src='http://d3js.org/d3.v3.js'></script>
<script src="js/index.js"></script>
</body>
</html>
style.css
#container{
background: #ddd;
width: 500px;
height:250px;
}
index.js
//svg
var svg=d3.select("#container")
.append("svg")
//width,height
.attr("width",500) //attribute
.attr("height",250)
d3.select("svg")
.append("g")
.attr("transform","translate(50,30)")
可以右键选择 edit as html 来看编辑效果
2. 绘制曲线
通过实际数据来生成曲线
index.js
//svg
var svg=d3.select("#container")
.append("svg")
//width,height
.attr("width",500) //attribute
.attr("height",250)
var g=d3.select("svg")
.append("g")
.attr("transform","translate(50,30)") //沿x轴偏移50px
var data=[1,3,5,7,8,4,3,7]
var line_generator=d3.svg.line()
.x(function(d,i){return i;}) //0,1,2,3,....
.y(function(d){return d;}) //1,3,5
d3.select("g")
.append("path") //<path d="M1,0L20,40L40,50L100,100L0,200"></path> 起始点是1,0,line到点20,40,line到点40,50
.attr("d",line_generator(data))
下面我们为了让上图中小小的曲线根据画布成比例的放大,我们重构一下index.js的代码
var width=500,
height=250,
margin={left:50,top:30,right:20,bottom:20},
g_width=width-margin.left-margin.right,
g_height=height-margin.top-margin.bottom;
//svg
var svg=d3.select("#container")
.append("svg")
//width,height
.attr("width",width) //attribute
.attr("height",height)
var g=d3.select("svg")
.append("g")
.attr("transform","translate("+margin.left+","+margin.top+")") //沿x轴偏移50px
var data=[1,3,5,7,8,4,3,7]
var scale_x=d3.scale.linear()
.domain([0,data.length-1])
.range([0,g_width])
var scale_y=d3.scale.linear()
.domain([0,d3.max(data)])
.range([0,g_height])
var line_generator=d3.svg.line()
.x(function(d,i){return scale_x(i);}) //0,1,2,3,....
.y(function(d){return scale_y(d);}) //1,3,5
d3.select("g")
.append("path") //<path d="M1,0L20,40L40,50L100,100L0,200"></path>
.attr("d",line_generator(data))
结果如下:
上面那个样式很难看,我们直接在google开发者工具中调整(注意:刷新后会消失,只是帮助我们看调整效果)
然后我们将样式复制到style.css中
但是我们需要的是一条曲线而不是直线,那么我们修改index.js,加入一行代码:
var line_generator=d3.svg.line()
.x(function(d,i){return scale_x(i);}) //0,1,2,3,....
.y(function(d){return scale_y(d);}) //1,3,5
<span style="color:#ff0000;">.interpolate("cardinal")</span> //让直线变成拟合的曲线
成功