简体   繁体   English

如何在d3.js中添加自定义刻度标签?

[英]How to add custom tick labels in d3.js?

I want to add custom tick labels on the x axis,like 1,2,3,4,3,2,1 in this pattern. 我想在x轴上添加自定义刻度标签,例如此模式中的1,2,3,4,3,2,1。 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. 解决这个问题需要一点技巧。

Cause 原因

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

Solution

  • Create linear scale with total item in the axis as domain [0, itemLength] 创建线性刻度,将轴上的项目总数作为域[0,itemLength]
  • While creating axis use tickFormat to find out the index of the element 创建轴时,使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM