d3坐标轴

1、绘制坐标轴

绘制svg

<div id = "container"></div>

----------

var svg_w = 500,  // svg的宽度
    svg_h = 400,  // svg的高度
    g_left = 50,  // 坐标系离svg的左边距
    g_top = 50, // 坐标系离svg的上边距
    g_w = svg_w - 2 * g_left, // 坐标系的宽度
    g_h = svg_h - 2 * g_top;  // 坐标系的高度

// 绘制svg    
var svg = d3.select('#container').append('svg')
  .style({
     svg_w,
    height: svg_h
  }); 

绘制横坐标

// 横坐标
var scale_x = d3.scale.linear()
  .domain([0, 10]) // 输入范围
  .range([0, g_w]); // 输出范围
var axis_x = d3.svg.axis().scale(scale_x);

svg.append('g')
  .call(axis_x)
  .classed('axis_x', true)
  .style({
    strokeWidth: '1',
    stroke: '#aaa',
    fill: 'none',
    transform: 'translate('+g_left+'px, '+(g_h+g_top)+'px)'
  });

绘制纵坐标

// 纵坐标
var scale_y = d3.scale.linear()
  .domain([0, 10])
  .range([g_h, 0]); // 由于浏览器的y轴和数学上的y轴相反,所有输出范围是[num, 0]
var axis_y = d3.svg.axis().scale(scale_y).orient('left');

svg.append('g')
  .call(axis_y)
  .classed('axis_y', true)
  .style({
    strokeWidth: '1',
    stroke: '#aaa',
    fill: 'none',
    transform: 'translate('+g_left+'px, '+g_top+'px)'
  });

2、 坐标轴的其他参数(自定义坐标轴)

var axis_x = d3.svg.axis().scale(scale_x)
  .orient('top')  // 刻度与坐标轴方向
  .ticks(5) // 分成5等分,有时d3会根据可用空间和它自己的计算多画几个或者少画几个
  .tickSubdivide(4) // 每个大刻度之间再画4个等分刻度
  .tickPadding(10)  // 刻度值与坐标轴之间的距离
  .tickFormat(function(v) { // 格式化刻度值
    return v + '天';
  });

3、 坐标轴单位

d3.select('g.axis_y').append('text')
  .text('价格(元)')
  .style({
    'transform': 'rotate(-90deg)',
    'text-anchor': 'end'  // 设置文本的排列属性startmiddleend
  })
  .attr('dy', '1em')

4、绘制网格线

// 竖直方向的线条
d3.selectAll('g.axis_x g.tick')
  .append('line')
  .attr({
    x1: 0,
    y1: 0,
    x2: 0,
    y2: -g_h
  })

// 水平方向的线条
d3.selectAll('g.axis_y g.tick')
  .append('line')
  .attr({
    x1: 0,
    y1: 0,
    x2: g_w,
    y2: 0
  })
原文地址:https://www.cnblogs.com/Zting00/p/7497653.html