首页 > 设计 > WEB开发 > 正文

d3坐标轴

2019-11-02 18:22:52
字体:
来源:转载
供稿:网友

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({ width: 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' // 设置文本的排列属性start/middle/end }) .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 })
上一篇:splice()方法功能

下一篇:31.提示标签

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表