D3 二维图表的绘制系列(七)堆叠面积图

上一篇: 基础折线图 https://blog.youkuaiyun.com/zjw_python/article/details/98210977

下一篇: 曲线图 https://blog.youkuaiyun.com/zjw_python/article/details/98478578

代码结构和初始化画布的Chart对象介绍,请先看 https://blog.youkuaiyun.com/zjw_python/article/details/98182540

本图完整的源码地址: https://github.com/zjw666/D3_demo/tree/master/src/lineChart/stackedAreaChart

1 图表效果

在这里插入图片描述

2 数据

date,total,food,transportation,education
Mon,120,30,40,50
Tue,200,20,80,100
Wed,150,20,50,80
Thu,80,10,30,40
Fri,70,15,20,35
Sat,110,10,30,70
Sun,130,20,50,60

3 关键代码

导入数据

d3.csv('./data.csv', function(d){
   
    return {
   
        date: d.date,
        total: +d.total,
        food: +d.food,
        transportation: +d.transportation,
        education: +d.education
    };
}).then(function(data){
   
.....

一些样式参数配置,与基础折线图类似

const config = {
   
        margins: {
   top: 80, left: 80, bottom: 50, right: 80},
        textColor: 'black',
        gridColor: 'gray',
        ShowGridX: [],
        ShowGridY: [50, 100, 150, 200, 250, 300, 350, 400],
        title: '堆叠面积图',
        pointSize: 5,
        pointColor: 'white',
        hoverColor: 'red',
        animateDuration: 1000
    }

尺度转换和布局函数定义,堆叠面积图和堆叠柱状图类似,都使用了d3.stack计算布局

/* ----------------------------尺度转换------------------------  */
    chart.scaleX = d3.scalePoint()
                    .domain(data.map((d) => d.date))
                    .range([0, chart.getBodyWidth()])
    
    chart.scaleY = d3.scaleLinear()
                    .domain([0, (Math.floor((d3.max(data, (d) => d.total) + d3.max(data, (d) => d.food) + d3.max(data, (d) => d.education) + d3.max(data, (d) => d.transportation))/10) + 1)*10])
                    .range([chart.getBodyHeight(), 0])

    chart.stack = d3.stack()
                    .keys(['total', 'food', 'transportation', 'education'])
                    .order(d3.stackOrderAscending)
                    .offset(d3.stackOffsetNone);

渲染线条,这里与基础折线图类似,使用插值和中间帧实现动画过渡效果

/* ----------------------------渲染线条------------------------  */
    chart.renderLines = function(){
   

        let lines = chart.body().selectAll('.line')
                    .data(chart.stack(data));

            lines.enter()
                    .append('path')
                    .attr('class', (d) => 'line line-' + d.key)
                .merge(lines)
                    .attr('fill', 'none')
                    .attr('stroke', (d,i) => chart._colors(i))
                    .transition().duration(config.animateDuration)
                    .attrTween('d', lineTween);
            
            lines.exit()
                    .remove
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值