轴上的自定义刻度大小(d3js) [英] Custom tick size on axis (d3js)

查看:1381
本文介绍了轴上的自定义刻度大小(d3js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在d3.js中创建一个svg x-y图表。是否可以根据tickValue创建不同长度的tick?

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

我已经创建了自己的tickFormat函数 myTickFormat .tickFormat([format])中使用,因为 [format] 应该是一个函数。但是不可能对 .innerTickSize([size])做同样的操作,它需要一个数字。

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.

例如如果我想要值70的时间更长,我想这样做:

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;
};

但是当我使用 myTickSize .innerTickSize()

var yScale = d3.scale.linear();
var yAxis = d3.svg.axis()
               .scale(yScale).orient("left")
               .innerTickSize(myTickSize);

我得到一个错误:属性x2 =NaN的值无效错误。

推荐答案

tickSize函数只能接受一个数字作为参数,而不是一个函数, 。

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.

例如:

http://fiddle.jshell.net/zUj3E/1/

键码: / p>

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;
    });

请注意,最大值和最小值处的刻度线也绘制为相同的< path> 作为轴线,因此缩短它们没有太大的影响。如果你不喜欢那种缺乏控制,当你设置轴时,声明外刻度为零长度。这将关闭路径的角落,但外部的ticks仍然会有线,你可以控制与其他tick线相同:

Note that the tick marks at the max and min values are also drawn as part of the same <path> 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)

示例: http://fiddle.jshell.net/zUj3E/2/

如果这不起作用,google的主要/次要刻度模式的例子。只要确保你看到的例子使用d3版本3:在版本2中添加了一些额外的tick相关的方法,不再支持。 查看此SO Q& A。

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.

这篇关于轴上的自定义刻度大小(d3js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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