问题
I have no idea of what I'm doing wrong at this point. scalePoint works and the values are in line with the axis, but scaleBand does for some reason shift left.
My fiddle: https://jsfiddle.net/go0r0yco/
Selected parts of the code from my file:
var x = d3.scaleBand()
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x);
var yAxis = d3.axisLeft()
.scale(y);
// the domain
x.domain(myData.map(function (d)
{
console.log(d.ball);
return d.ball;
}));
y.domain([0, d3.max(myData, function (d)
{
//console.log("our maxtime" + d.finaltime);
return d["ball data"]["final time"];
})]);
// the scatterplot
myChart.selectAll("dot")
.data(myData)
.enter()
.append("circle")
.style("fill", "orange")
.attr("r", 5)
.attr("cx", function (d)
{
return x(d.ball);
})
.attr("cy", function (d)
{
if (!d["ball data"]["final time"]) { return height/2 } else {
return y(d["ball data"]["final time"]);}
});
回答1:
The band scale doesn't shift the value to the left. What you're getting in your chart is the expected behaviour, and that's exactly the difference between scalePoint
and scaleBand
. In a band scale:
Discrete output values are automatically computed by the scale by dividing the continuous range into uniform bands (emphasis mine).
Right now, for each circle, you're getting the start of the band:
return x(d.ball);
So, to have an output similar to a point scale, you should divide the band by 2:
return x(d.ball) + x.bandwidth()/2;
Here is your fiddle: https://jsfiddle.net/jxdsqqwy/
来源:https://stackoverflow.com/questions/41037539/scaleband-shifts-the-values-left