美文网首页D3.js--从陌生到熟悉
Manipulating data like a boss wi

Manipulating data like a boss wi

作者: 雷朝建 | 来源:发表于2018-04-21 11:18 被阅读0次

    数据准备

    https://github.com/leicj/d3/blob/master/src/components/bubble/data.js

    源码

    https://github.com/leicj/d3/tree/master/src/components/bubble

    效果图

    image.png

    这里主要有三部分组成:

    • 散点图
    • x/y坐标轴
    • 网格

    散点图

        const width = 500;
        const height = 500;
        const margin = 50;
        const svg = d3.select('svg').attr('width', width).attr('height', height);
        const x = d3.scaleLinear().domain([0, 5]).range([margin, width - margin]);
        const y = d3.scaleLinear().domain([-10, 10]).range([height - margin, margin]);
        const r = d3.scaleLinear().domain([0, 500]).range([0, 20]);
        const o = d3.scaleLinear().domain([10000, 100000]).range([.5, 1]);
        const c = d3.scaleOrdinal(d3.schemeCategory10).domain(["Africa", "America", "Asia", "Europe", "Oceania"]);
    
        const bubble = svg.selectAll('circle').data(country)
          .enter().append('circle')
          .attr('cx', (d, i) => x(GERD[i]))
          .attr('cy', (d, i) => y(growth[i]))
          .attr('r', (d, i) => r(Math.sqrt(population[i])))
          .style('fill', (d, i) => c(continent[i]))
          .style('opacity', (d, i) => o(GDPcap[i]))
          .append('title')
          .text(String);
    

    这里x,y,r,o,c分别为函数, 将domain和range对应起来.

    x/y坐标轴

        const gx = d3.select('svg').append('g').attr('transform', `translate(0, ${height - margin})`);
        const gy = d3.select('svg').append('g').attr('transform', `translate(${margin}, 0)`);
    
        const xAxis = d3.axisBottom(x);
        const yAxis = d3.axisLeft(y);
    
        gx.call(xAxis);
        gy.call(yAxis);
    

    这里由于margin的存在, 所以x/y坐标轴可见.

    网格线

        svg.selectAll('.h').data(d3.range(-8, 10, 2))
          .enter().append('line')
          .attr('class', 'h')
          .style('stroke', 'black')
          .style('stroke-dasharray', '4 4')
          .style('stroke-width', 1)
          .style('stroke-opacity', .5)
          .attr('x1', margin).attr('y1', y)
          .attr('x2', width - margin).attr('y2', y);
    
        svg.selectAll('.v').data(d3.range(.5, 5, .5))
          .enter().append('line')
          .attr('class', 'v')
          .style('stroke', 'black')
          .style('stroke-dasharray', '4 4')
          .style('stroke-width', 1)
          .style('stroke-opacity', .5)
          .attr('x1', x).attr('y1', height - margin)
          .attr('x2', x).attr('y2', margin);
    

    相关文章

      网友评论

        本文标题:Manipulating data like a boss wi

        本文链接:https://www.haomeiwen.com/subject/qsztlftx.html