<html>
<head>
<meta charset="utf-8">
<title>给柱形图添加比例尺</title>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width=300;//画布的宽度
var height=300;//画布的高度
var svg=d3.select("body") //选择文档中的body元素
.append("svg")//添加一个svg元素
.attr("width",width) //设定宽度
.attr("height",height) //设定高度
var dataset=[2.5,2.1,1.7,1.3,0.9];
var linear=d3.scale.linear()//定义一个线性比例尺
.domain([0,d3.max(dataset)])
.range([0,300]);//dataset中最小的值映射成0,最大的值映射成250
var rectHeight=25;//每个矩形所占的像素高度
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x",20)
.attr("y",function(d,i){
return i*rectHeight;
})
.attr("width",function(d){
return linear(d);
})
.attr("height",rectHeight-2)
.attr("fill","steelblue")
</script>
</body>
</html>
演示地址:http://runjs.cn/detail/oaj1pnql
d3js比例尺
最新推荐文章于 2021-09-22 16:29:17 发布