一、页面引入
<!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>D3绘制折线</title>
<link href="../css/polyLine.css">
</head>
<body>
<div id="container-polyLine"></div>
<div id="container-area"></div>
<script src="../lib/d3-5.9.7.min.js"></script>
<script src="../js/polyLine.js"></script>
</body>
</html>
二、折线图绘制
//绘制折线图
function polyLine(volume, group) {
let svgAttr = {width: 800, height: 500}
let gAttr = {left: 30, top: 30, right: 30, bottom: 30}
let svg = d3.select('#container-polyLine').append('svg').attr('width', svgAttr.width).attr('height', svgAttr.height);
let g = svg.append('g').attr('transform', 'translate('+gAttr.left+','+gAttr.top+')');
let xScale = d3.scaleBand().domain(group).rangeRound([0, svgAttr.width - gAttr.left - gAttr.right]);
let xAxis = d3.axisBottom(xScale);
let yScale = d3.scaleLinear().domain([0, d3.max(volume)]).range([svgAttr.height - gAttr.top - gAttr.bottom, 0]);
let yAxis = d3.axisLeft(yScale);
g.append('g').attr('transform', 'translate(0,'+(svgAttr.height - gAttr.top - gAttr.bottom)+')').call(xAxis);
g.append('g').attr('transform', 'translate(0,0)').call(yAxis);
let line_generator = d3.line().x(function (d, i) {
return xScale(group[i]);
}).y(function(d, i) {
return yScale(d);
})
//折线变得圆滑,如果不需要可以去掉
.curve(d3.curveMonotoneX);
g.append('path').attr('d', line_generator(volume)).attr('fill', 'none').attr('stroke', 'blueviolet')
.attr('stroke-width', '2').attr('cursor', 'pointer').on('mouseover', function (d, i) {
d3.select(this).transition().duration(100).attr('stroke', '#CB7730');
}).on('mouseout', function (d, i) {
d3.select(this).transition().duration(100).attr('stroke', 'blueviolet');
}).on('click', function () {
alert('曲线事件已触发!');
});
}
window.onload = function () {
let sales_volume_orange = [20,35,18,16,13,12,9,11,19,27,30,26];
let monthes = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
polyLine(sales_volume_orange, monthes);
}