d3设置line长度,轴上的自定义刻度大小(d3js)

在d3.js中创建SVG图表时,如何根据刻度值设置不同长度的刻度线?虽然可以自定义刻度格式,但不能直接为innerTickSize()使用函数。一种解决方法是在绘制轴后,选择所有刻度线并根据数据值调整它们的长度。这需要在每次轴重绘后执行。另一种方法是在设置轴时将外层刻度大小设为0,以控制主要和次要刻度的长度。
摘要由CSDN通过智能技术生成

I am creating a svg x-y-chart in d3.js. Is it possible to create ticks of different lengths depending on tickValue?

I have made my own tickFormat function myTickFormat and use that in .tickFormat([format]) and that works fine because [format] is expected to be a function. But it is not possible to do the same with .innerTickSize([size]), which expects a number.

E.g. if I want the tick at value 70 to be longer I want to do something like this:

var myTickSize = function(d) {

if (d === 70) { return 20;}

return 6;

};

But when I use myTickSize as argument to .innerTickSize():

var yScale = d3.scale.linear();

var yAxis = d3.svg.axis()

.scale(yScale).orient("left")

.innerTickSize(myTickSize);

I get an Error: Invalid value for attribute x2="NaN" error for each tick.

解决方案

The tickSize function can only accept a number as argument, not a function, but there are other solutions.

The easiest approach? After the axis is drawn, select all the tick lines and resize them according to their data value. Just remember that you'll have to do this after every axis redraw, as well.

Key code:

d3.selectAll("g.y.axis g.tick line")

.attr("x2", function(d){

//d for the tick line is the value

//of that tick

//(a number between 0 and 1, in this case)

if ( (10*d)%2 ) //if it's an even multiple of 10%

return 10;

else

return 4;

});

Note that the tick marks at the max and min values are also drawn as part of the same as the axis line, so shortening them doesn't have much effect. If you don't like that lack of control, declare the "outer" ticks to have zero length when you set up the axis. That turns off the corners of the path, but the outer ticks will still have lines that you can control the same as the other tick lines:

var axis = d3.svg.axis()

.tickSize(10,0)

If that doesn't work, google for examples of major/minor tick patterns. Just make sure the example you're looking at uses d3 version 3: there were a few extra tick-related methods added in version 2 that are no longer supported. See this SO Q&A.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值