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]
verticalShapeChart(data,"#container") //D3生成竖直柱状图表
/*** @desc 竖直柱状图表
*/
function verticalShapeChart(data, container) {
var bar_height = 50,
bar_padding = 10,
svg_height = (bar_height+bar_padding) * data.length,
svg_width = 500
var scale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, svg_width])
//添加svg元素,设置宽度和高度
var svg = d3.select(container)
.append("svg:svg")
.attr("width", svg_width)
.attr("height", svg_height)
//选择所有的g元素,设置平移位置
var bar = svg.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d, i){ return "translate(0,"+(bar_height+bar_padding)*i+")";})
//添加矩阵元素,设置填充宽度高度
bar.append("rect")
.attr({
"width": function(d){ return scale(d); } ,
"height": bar_height
})
.style("fill", "steelblue")
//设置图表文字
bar.append("text")
.text(function(d){ return d; })
.attr({
"x": function(d){ return scale(d); },
"y": bar_height/2,
})
.style("text-anchor", "end")
}