简体   繁体   English

D3轴标尺

[英]D3 axis lable scale

trying to learn D3 and on the label axis seem to be stacked upon one another. 尝试学习D3并在标签轴上似乎相互堆叠。 I have tried to turn the scale calls into reusable functions however this may be exacerbating the issue. 我试图将scale调用转换为可重用的函数,但这可能使问题更加严重。 The data: 数据:

data=[];
data.push({'label':'#1','cost':15000,'saving':18000});
data.push({'label':'#2','cost':40000,'saving':65000});
data.push({'label':'#3','cost':55000,'saving':80000});
data.push({'label':'#4','cost':15000,'saving':30000});

The scale: 规模:

function getY(d){
    return yScale = d3.scaleBand()
        .domain(d3.range(0, d.length))
        .range([0, (height-20)])
        .paddingInner(0.1)
        .paddingOuter(0.1)
}

Trying to build the axis: 尝试构建轴:

labels=[]
$.each(data,function(){
    labels.push(this.label);
})
var hAxis = d3.axisRight()
    .scale( getY(data) )
    .tickValues( labels )

Everything seems to be working but the labels seem to be receiving something incorrect on the translate: 一切似乎都正常,但标签似乎在翻译中接收到不正确的内容:

<g class="tick" opacity="1" transform="translate(0,NaN)"><line stroke="#000" x2="6">

Where is the NaN being received from, I assume an incorrectly coded scale. 我是从哪里收到NaN的,我假设编码比例不正确。

Fiddle: https://jsfiddle.net/L9mmy5d6/ 小提琴: https : //jsfiddle.net/L9mmy5d6/

tickValues specifies which values should have ticks, not what those ticks should look like. tickValues指定应该具有刻度的值,而不是那些刻度。 You can only specify values in the domain of the scale here. 您只能在此处在比例域中指定值。

If you have a standardized change you want (say, adding # to each number (and incrementing by one so that the numbers start at 1)), then you could use: 如果您想要进行标准化的更改(例如,在每个数字上添加#(并增加一个,以便数字从1开始)),则可以使用:

var hAxis = d3.axisRight()
    .scale( getY(data) )
    .tickFormat(function(d,i) { return "#"+(d+1) } )

( fiddle ) 小提琴

Alternatively, if you want to pursue the same approach that you have, you could use something like: 另外,如果您想采用与您相同的方法,则可以使用以下方法:

var hAxis = d3.axisRight()
    .scale( getY(data) )
    .tickFormat(function(d,i) { return labels[i] })

( fiddle ) 小提琴

Keep in mind that your number of ticks should correspond to the the number of labels if using the index. 请记住,如果使用索引,则刻度数应与标签数相对应。 You could also use d to set the label in this case, as the tick marks correspond to the index. 在这种情况下,您还可以使用d设置标签,因为刻度线对应于索引。

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

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