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]
horizontalShapeWithAxisChart(data,"#container") //D3生成面积图表
/*** @desc 水平柱状图表+坐标轴
*/
function horizontalShapeWithAxisChart(data, container) {
var width = 600,
height = 250,
margin = {left:80, top:30, right:30, bottom:30},
svg_width = width+margin.left+margin.right,
svg_height = height+margin.top+margin.bottom
var scale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([height, 0])
var scale_x = d3.scale.ordinal()
.domain(data.map(function(d,i){ return i; }))
.rangeBands([0,width], 0.1)
//添加svg元素,设置宽度和高度
var svg = d3.select(container)
.append("svg:svg")
.attr("width", svg_width+50)
.attr("height", svg_height)
//添加chart元素,平移left和top
var chart = svg.append("g")
.attr("transform", "translate("+margin.left+","+margin.top+")")
//添加X、Y坐标轴
var x_axis = d3.svg.axis().scale(scale_x),
y_axis = d3.svg.axis().scale(scale).orient("left")
chart.append("g")
.call(x_axis)
.attr("transform", "translate(0,"+height+")")
.append("text")
.attr("transform", "translate("+width+",0)")
.text("时间(天)")
chart.append("g")
.call(y_axis)
.append("text")
.text("销售总价(¥)")
.attr("transform", "translate(-15,-15)")
//选择所有的g元素,设置平移位置
var bar = chart.selectAll(".bar")
.data(data)
.enter()
.append("g")
.attr("class", "bar")
.attr("transform", function(d, i){ return "translate("+scale_x(i)+",0)";})
//添加矩阵元素,设置填充宽度高度
bar.append("rect")
.attr({
"y": function(d){ return scale(d); },
"width": scale_x.rangeBand(),
"height": function(d){ return height - scale(d); }
})
.style("fill", "steelblue")
//设置图表文字
bar.append("text")
.text(function(d){ return d; })
.attr({
"y": function(d){ return scale(d); },
"x": scale_x.rangeBand()/2,
// "dy": 15 //文字位置
})
.style("text-anchor", "middle")
}