一、页面中引入相关函数
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>柱状图</title>
</head>
<body>
<div id="container"></div>
<script src="../lib/d3-5.9.7.min.js"></script>
<script src="../js/histogram.js"></script>
</body>
</html>
二、单柱体柱状图绘制函数
//绘制柱状图
function histogram() {
let svgAttr = {width:700,height:500};
let marge = {top:60,bottom:60,left:60,right:60};
let dataset = [10,20,30,23,13,40,27,35,20,5];
let fruts = ['apple', 'pear', 'watermelon', 'peach', 'apricot', 'tomato', 'banana', 'pineapple', 'grape', 'litchi'];
let svg = d3.select('#container').append('svg').style('width', svgAttr.width).style('height', svgAttr.height);
let g = svg.append('g').attr('transform', 'translate('+marge.top+','+marge.left+')');
//X轴比例尺
let xScale = d3.scaleBand().domain(fruts).rangeRound([0, svgAttr.width-marge.left-marge.right]);
let xAxis = d3.axisBottom(xScale);
//Y轴比例尺
let yScale = d3.scaleLinear().domain([0, d3.max(dataset)]).range([svgAttr.height-marge.top-marge.bottom, 0]);
let yAxis = d3.axisLeft(yScale);
g.append('g').attr('transform', 'translate('+0+','+(svgAttr.height-marge.bottom-marge.top)+')').call(xAxis)
.selectAll('text').attr('transform', 'rotate(45 -20 20)');
g.append('g').attr('transform', 'translate(0,0)').call(yAxis)
.selectAll('line').attr('stroke-width', '0.5px').attr('x1', 0).attr('x2', function () {
return svgAttr.width-marge.left-marge.right;
});
//绘制柱体
let rectWidth = 30;
let gRect = g.selectAll('.rect').data(dataset).enter().append('g');
gRect.append('rect').attr('x', function (d, i) {
return xScale(fruts[i]) + rectWidth/2;
}).attr('y', function (d, i) {
let min = yScale.domain()[0];
return yScale(min);
}).attr('width', function () {
return rectWidth;
}).attr('height', function () {
return 0;
}).attr('fill', '#22A7F2').attr('cursor', 'pointer').on('mouseover', function (d, i) {
d3.select(this).transition().duration(100).attr('fill', '#2C81F3');
}).on('mouseout', function (d, i) {
d3.select(this).transition().duration(100).attr('fill', '#22A7F2');
}).on('click', function () {
alert('事件已触发!');
})
.transition().duration(1000).delay(function(d,i){
return i*100;
})
.ease(d3.easeBack)
.attr("y",function(d){
return yScale(d);
})
.attr("height",function(d){
return svgAttr.height-marge.top-marge.bottom-yScale(d);
});
//柱体顶部绘制文字
gRect.append('text').attr('x', function (d, i) {
return xScale(fruts[i])+rectWidth/2;
}).attr('y', function () {
let min = yScale.domain()[0];
return yScale(min);
}).attr('font-size', '12px').attr('fill', '#404040')
.text(function (d) {
return d;
}).transition().duration(1000).delay(function (d, i) {
return i*100;
}).ease(d3.easeBack).attr('x', function (d, i) {
return xScale(fruts[i])+rectWidth/2;
}).attr('y', function (d) {
return yScale(d)-1;
});
}
window.onload = function () {
histogram();
}
详情可联系 q317068568