交互式数据可视化-D3.js(四)形状生成器

形状生成器

线段生成器

var linePath = d3.line() - 使用默认的设置构造一个 line 生成器。

linePath.x() - 如果指定了 x 则将 x 访问器设置为指定的函数或数值并返回当前 line 生成器。如果没有指定 x 则返回当前 x 访问器,默认为:


function x(d) {
    return d[0];
}

linePath.y() - 如果指定了 y 则将 y 访问器设置为指定的函数或数值并返回当前 line 生成器。如果没有指定 y 则返回当前 y 访问器,默认为:


function y(d) {
    return d[1];
}

linePath.curve() - 如果指定了 curve 则表示设置当前的曲线插值方法并返回线条生成器。

使用方法如下:


var lines = [[80, 80], [200, 100], [200, 200], [100, 200]]
var linePath = d3.line().curve(d3.curveCatmullRom.alpha(0.5));
var drawLine = d3.select('#line').append('svg').attr('width', 400).attr('height', 300);
drawLine.append('path').attr('d', linePath(lines)).attr('stroke', 'black').attr('stroke-width', '3').attr('fill', 'none');

区域生成器

在需要生产折线或曲线下方面积的时候,使用区域生成器, 数据访问器有x(), x0(), x1(), y(), y0(), y1()六个,不需要全部使用,其他方法与线段生成器基本类似,使用方法如下:


var areas = [80, 120, 130, 70, 60, 90]
var dragArea = d3.area();=
dragArea.x(function(d, i){
    return 20 + i * 30;
 })

dragArea.y0(function(d, i){
    return 400 / 2;
})

dragArea.y1(function(d, i){
    return 400 / 2 - d;
})
dragArea.curve(d3.curveCatmullRom.alpha(0.5))
var drawLine = d3.select('#line').append('svg').attr('width', 400).attr('height', 300);
drawLine.append('path').attr('d', dragArea(areas)).attr('stroke', 'black').attr('stroke-width', '3').attr('fill', '#f0f');

弧生成器

弧生成器可凭借起始角度,终止角度,内半径, 外半径等,生产弧线的路径,因此在制作饼状图,弦图等图表的时候很常用。常用方法有:

var arc = d3.arc() - 设置弧生成器

arc.innerRadius(80); - 设置环的内半径

arc.startAngle(0) - 设置起始角度

arc.endAngle(Math.PI) - 设置终止角度

arc.cornerRadius(10) - 设置拐角半径

大致的使用方法:


var arc=d3.arc().innerRadius(80)outerRadius(100).startAngle(0).endAngle(Math.PI);
var drawLine = d3.select('#line').append('svg').attr('width', 400).attr('height', 300);
drawLine.append('path')
    .attr('d', arc())
    .attr('stroke', 'black')
    .attr('stroke-width', '3')
   .attr('fill', '#f0f')
   .attr('transform', 'translate(200, 150)');

弦生成器

弦生成器根据两段弧来绘制,需要以下几个方法:

var chord = d3.ribbon() - 设置弦生成器

chord.source() - 设置起始弧度

chord.target() - 设置终止弧

chord.radius() - 设置弧半径

chord.startAngle() - 设置弧的起始角度

chord.endAngle() - 设置弧的终止角度

如果使用默认访问器,生成弦图,其数据格式为:


 {
    source: {
        startAngle: 0.2,
        endAngle: Math.PI * 0.3,
        radius: 100
    },
    target: {
        startAngle : Math.PI * 1,
        endAngle: Math.PI * 1.6,
        radius: 100
    }
}

也可以更改方法,使用自定义的数据:


var data = {
    a: {
        a1: 0.2,
        a2: Math.PI * 0.3,
    },
    b: {
        a1 : Math.PI * 1,
        a2: Math.PI * 1.6,
    }
}

var chord = d3.ribbon();
chord.source(function(d){
    return d.a
})
chord.target(function(d){
    return d.b
})
chord.radius(100);
chord.startAngle(function(d){
    return d.a1
})
chord.endAngle(function(d){
    return d.a2
})

原文地址:https://segmentfault.com/a/1190000016897684

猜你喜欢

转载自www.cnblogs.com/lalalagq/p/9903487.html