index.html(图表页面)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container"></div>
</body>
<script src="https://d3js.org/d3.v3.js"></script>
<script src="index.js"></script>
</html>
index.js(JS代码)
var data = [0,34.45,45.534,556,76,87,234,234]
generateLineChart(data,"#container",800,250,"时间(天)","销售总价(¥)","svg_price","g_price") //D3生成线性图表
/**
* @desc D3生成线性图表
*/
function generateLineChart(data,container,width,height,x_text,y_text,svg_class,g_class) {
// var width = 500 //contianer元素宽度
// var height = 250 //contianer元素高度
var margin = {left:50,top:30,right:20,bottom:20} //contianer元素边距
var g_width = width - margin.left - margin.right //svg元素高度
var g_height = height - margin.top - margin.bottom //svg元素宽度
//在id为contanier的容器里添加svg元素,并设置宽度和高度
var svg = d3.select(container)
.append("svg:svg")
.attr("class",svg_class)
.attr("width", width+50)
.attr("height", height)
//获得添加后的svg元素,设置边距
var g = d3.select("."+svg_class)
.append("g")
.attr("class", g_class)
.attr("transform", "translate("+margin.left+","+margin.top+")")
//指定x,y缩放比例
var x_scale = d3.scale.linear()
.domain([0, data.length-1])
.range([0, g_width])
var y_scale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([g_height, 0])
//d元素属性值x,y坐标
var line_generator = d3.svg.line()
.x(function(d,i){ return x_scale(i); })
.y(function(d){ return y_scale(d); })
// .interpolate("cardinal") //是否曲线
//给svg元素添加path并设置d属性
d3.select("."+g_class)
.append("path")
.attr("d", line_generator(data))
//添加横轴坐标轴
var x_axis = d3.svg.axis().scale(x_scale),
y_axis = d3.svg.axis().scale(y_scale).orient("left")
//添加x坐标轴并设置文字描述
g.append("g")
.call(x_axis)
.attr("transform", "translate(0,"+g_height+")")
.append("text")
.text(x_text)
.attr("transform", "translate("+g_width+",0)")
//添加y坐标轴并设置文字描述
g.append("g")
.call(y_axis)
.append("text")
.text(y_text)
.attr("transform", "translate(-15,-15)")
// .attr("transform", "rotate(-90)")
// .attr("text-anchor", "end")
// .attr("dy", "1em")
}