d3.js——折线图(v5)

一、页面引入
<!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);
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值