如何在d3.js中添加自定义刻度标签? [英] How to add custom tick labels in d3.js?

查看:296
本文介绍了如何在d3.js中添加自定义刻度标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在x轴上添加自定义刻度标签,例如此模式中的1,2,3,4,3,2,1.但是我使用的代码没有显示出递减的数字.

I want to add custom tick labels on the x axis,like 1,2,3,4,3,2,1 in this pattern. But the code that I am using doesn't show the decreasing numbers.

var margin = {
    top: 100,
    right: 100,
    bottom: 100,
    left: 100
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .domain([1, 2, 3, 4, 5, 4, 3, 2, 1])
    .rangePoints([0, width]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
.attr("class", "x axis")
.call(xAxis);

任何帮助将不胜感激.谢谢.

Any kind of help would be appreciated. Thanks.

推荐答案

解决此问题所需的小技巧.

Little hack it needed to solve this issue.

原因

  • d3.scale.ordinal(),纯数学逻辑中的域计算.每个 与范围关联的域. (f(x)= y).
  • 不允许重复,因为这会造成歧义
  • d3.scale.ordinal(), domain calculation in purely mathematical logic. Each domain associated with a range. ( f(x)=y ).
  • Duplication not allowed because it will make ambiguity

解决方案

  • 创建线性标尺,以轴上的总项目为域[0,itemLength]
  • 在创建轴时,使用tickFormat查找元素的索引

var margin = {
	top: 100,
	right: 100,
	bottom: 100,
	left: 100
},
width = 560 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var xdata = ["1", "2", "3", "4", "5", "4", "3", "2", "1", "0"];

var linear = d3.scale.linear()
	.domain([0, 10])
	.range([0, width]);

var xAxis = d3.svg.axis()
	.scale(linear)
	.orient("bottom");

var axis = d3.svg.axis()
	.scale(linear)
	.orient("top")
	.ticks(10)
	.tickFormat(function (d) {
		return xdata[d];
	});

var svg = d3.select("body").append("svg")
	.attr("width", width + margin.left + margin.right)
	.attr("height", height + margin.top + margin.bottom)
	.append("g")
	.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
.attr("class", "x axis")
.call(axis);

.axis path, line {
  fill: none;
  stroke: #000;
  stroke-linecap: round;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

这篇关于如何在d3.js中添加自定义刻度标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆