我一直在制作图表,这里是小提琴: https://jsfiddle.net/lucksp/crwb4v5u/
我有" bins" Xaxis& amp;的数据基于15分钟增量的条形图。
现在我有垂直线工具提示,我注意到工具提示和工具提示之间的0:00
时间不一样。条形图本身:第一个刻度不是0:00,线条会说1:00(取决于窗口的大小,因为它的宽度基于父div)。
在这里你可以看到一个宽大的窗口: 在这里,您可以看到一个狭窄的窗口: 窗户越窄,比例似乎就越大。
示例数据:
[{"hour":"0:00","inProgress":3,"inQueue":0,"sum":3,"maxCapacity":6},{"hour":"0:15","inProgress":5,"inQueue":3,"sum":8,"maxCapacity":5}
设置比例:
xScale = d3.scale.ordinal()
.domain(dataSet.map(function(d) {
return d.hour;
}))
.rangeRoundBands([0, innerWidth], 0.1, 0);
设置xAxis:
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.tickSize(2)
.tickValues(['0:00', '2:00', '4:00', '6:00', '8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00']);
追加轴:
g.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + innerHeight + ')')
.call(xAxis);
创建栏:
g.selectAll('.bar')
.data(dataSet)
.enter().append('rect')
.attr('class', function(d, i) {
return 'bar inProgress_inQueue';
})
.attr('id', function(d, i) {
return 'bar_' + i + '_' + d.hour;
})
.attr('x', function(d) {
return xScale(d.hour);
})
.attr('y', function(d) {
return yScale(d.sum);
})
.attr('height', function(d) {
return innerHeight - yScale(d.sum);
})
.attr('width', xScale.rangeBand())
计算工具提示垂直线的交点。似乎从图表最左边正确开始的数据:
.on('mousemove', function(d, i) {
if (d3.select('.tooltip-table')) {
d3.select('.tooltip-table').remove();
}
var yPos = d3.mouse(this)[1];
var xPos = d3.mouse(this)[0];
var leftEdges = xScale.range();
var width = xScale.rangeBand();
var j;
for (j = 0; xPos > (leftEdges[j] + width); j++) {}
//do nothing, just increment j until case fails
var selected;
i = bisectDate(dataSet, leftEdges[j]); // returns the index to the current data item
if (j < dataSet.length) {
selected = (dataSet[j]);
} else {
return false;
}
我尝试通过编辑来移动栏的开头:
.attr('x', function(d) {
return xScale(d.hour) - margin.left; // but this does not work
})
我在xScale上有0个外部填充。
设置错误以移动左侧的图表&amp;右边?
再次感谢。
答案 0 :(得分:1)
只需在.rangeRoundBands
中将.rangeBands
更改为xScale
,就像这样:
xScale = d3.scale.ordinal()
.domain(dataSet.map(function(d) {
return d.hour;
}))
.rangeBands([0, width], 0.1, 0);
另请注意.rangeBands
有另一个参数,即外部填充。