使用D3.js绘制顺化曲线图面积图表
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen" type="text/css"/>
</head>
<body>
<div id="container"></div>
<script src="http://d3js.org/d3.v3.js" type="text/javascript"></script>
<script src="js/index.js" type="text/javascript"></script>
</body>
</html>
index.js
// 定义svg的宽度和高度
var width = 500,
height = 250,
margin = {left:50,top:30,right:20,bottom:20},
// 图表的宽度=svg的宽度减去margin
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")
// 设置x,y轴偏移量
.attr("transform","translate(" +margin.left+","+ margin.top +")")
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([g_height,0])
var area_generator = d3.svg.area()
// d表示传进来的数据 i表示数据的下标
.x(function(d,i){return scale_x(i);}) // 0,1,2,3
.y0(g_height) // 1,3,5
.y1(function(d){return scale_y(d);})
// 去除线的棱角 使其顺滑
.interpolate("cardinal")
g
.append("path")
// d 是 path data的缩写 将data数据传人
.attr("d",area_generator(data)) // d = "M1,0L20,40L40,50L100,100L0,200"
// 填充颜色
.style("fill","steelblue")
// 生成坐标轴
var x_axis = d3.svg.axis().scale(scale_x),
// y轴在左侧
y_axis = d3.svg.axis().scale(scale_y).orient("left");
g.append("g")
.call(x_axis)
.attr("transform","translate(0,"+ g_height +")")
g.append("g")
.call(y_axis)
//添加坐标轴叙述
.append("text")
.text("Price($)")
.attr("transform","rotate(-90)")
.attr("text-anchor","end")
.attr("dy","1em")
style.css
#container {
background: #ddd;
width: 500px;
height: 250px;
}
path {
fill:none;
stroke: #4682B4;
stroke-width:2;
}
/* 设置坐标样式 */
.domain,tick line {
stroke:gray;
stroke: width;
}