trying to learn D3 and on the label axis seem to be stacked upon one another. I have tried to turn the scale calls into reusable functions however this may be exacerbating the issue. 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.
Fiddle: https://jsfiddle.net/L9mmy5d6/
tickValues
specifies which values should have ticks, not what those ticks should look like. 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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.