d3 绘制面积图

 

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>svg</title>
        <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
        <style type="text/css">
            svg{
                background-color: #DDD;
            }
            
            .axis line,.axis path{
                fill:none;
                stroke:black
            }
        </style>
    </head>
    <body>
        
    </body>
    
    <script type="text/javascript">
        // 绘制面积图
        let width=500,height=500,num=30;
        
        // 定义数据源 学员成绩
        let score=[60,50,80,35,70,40]
        
        // 绘制svg
        let svg = d3.select('body').append('svg').attr('width',width).attr('height',height)
        
        // 创建g元素 包裹作用
        let g = svg.append('g').attr('transform',`translate(${num},${num})`)
        
        // 创建比例尺
        let scaleX = d3.scale.linear().domain([0,score.length-1]).range([0,width-num*2]);
        // let scaleY = d3.scale.linear().domain([0,d3.max(score)]).range([0,height-num*2]);
        let scaleY = d3.scale.linear().domain([0,d3.max(score)]).range([height-num*2,0]);
        
        // 构造曲面面积生成器  x y0 y1
        let area = d3.svg.area()
                    .x((d,i)=>{return scaleX(i)})
                    // .y0((d,i)=>{return 0})
                    .y0((d,i)=>{return height-num*2})
                    .y1((d,i)=>{return scaleY(d)})
                    .interpolate('cardinal')
                    
        // 绘制路径  通过路径绘制面积图形  path d 
        let color = d3.scale.category20()
        g.append('path')
            .attr('d',(d,i)=>{
                console.log(area(score))
                // M0,60L1,50L2,80L3,35L4,70L5,40L5,0L4,0L3,0L2,0L1,0L0,0Z
                return area(score)
            })
            .attr('fill','steelblue');
            
        
        // 生成坐标轴
        let x = d3.svg.axis().scale(scaleX)
        let y = d3.svg.axis().scale(scaleY).orient('left')
        
        g.append('g').attr('class','axis').call(x).attr('transform',`translate(0,${height-num*2})`)
        g.append('g').attr('class','axis').call(y)
        
        
        
    </script>

</html>

 

posted @ 2020-11-15 11:42  小不点灬  阅读(197)  评论(0编辑  收藏  举报