当我在下面的可视化中将所有这些条形图转换为折线图时。
我已在 buildAlpha 函数中的代码中添加了附加片段,该函数正在创建与可视化相关的所有栏。
但是,我无法在 DOM 中看到路径或行标记。
请帮我将所有这些条形图更改为折线图,并向各自的图表添加 y 轴
var line = d3.svg.line()
.x(function (d) {
return axes.timeX(new Date(d.date));
})
.y(function (d, i, j) {
return axes[keys[j] + 'Y'](d[keys[j]]);
})
.interpolate("basis");
var area = d3.svg.area()
.x(function (d) {
return axes.timeX(new Date(d.date));
})
.y0(108)
.y1(function (d) {
return axes[keys[j] + 'Y'](d[keys[j]]);
});
bars.append("path")
.attr("class", "area")
.attr("d", area);
bars.append("path")
.attr("class", "line")
.attr("d", function (d, i) {
return line(d['Air']);
});
已更新Fiddle与折线图。
但是无法获取条形图中提供的鼠标悬停线和工具提示
最佳答案
更新的 jsfiddle 可用 here 。除了折线图部分之外,我还执行了以下步骤:
创建一个 scales
对象以获取每个图表一个比例:
var scales = {};
fields.forEach(function(f){
var currentData = test.filter(function(d){return d.name===f;})[0].data;
scales[f]= d3.scale.linear()
.domain([0, d3.max(currentData, function(d) {return d.value})])
.range([lineHeight, 0])
.nice();
});
将 mousemove
添加到调度:
var dispatch = d3.dispatch('hideTooltip', 'iTooltip', 'mousemove');
向每个图表附加文本以显示工具提示:
alphaWrap.append('text')
.classed('tooltip', true)
.style('text-anchor', 'end')
.style('fill', function(d){return colorScale(d.name)});
在每个图表上附加一个 rect
以订阅 mousemove
事件。
当鼠标移动时,我获取它的位置,计算相应的日期,然后调度它:
alphaWrap.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', xScale.range()[1])
.attr('height', lineHeight)
.style('pointer-events', 'all')
.style('fill', 'transparent')
.on('mousemove', function(d,i){
var mouse=d3.mouse(this);
var date = xScale.invert(mouse[0]);
dispatch.mousemove(date);
});
在所有 3 个图表上添加一行:
d3.select('#chart-container')
.append('line')
.classed('tooltip', 'true')
.style('stroke', 'darkgray')
.attr('x1',90)
.attr('x2',90)
.attr('y1',0)
.attr('y2',fields.length*plotHeight);
对 dispatch
mousemove
事件使用react
我创建了一个bisector
查找图表数据数组中最接近日期的索引。
感谢日期和,平分线,可以适当移动线条,并可以显示tooltip的值
var bisector = d3.bisector(function(d){return d.date}).right;
dispatch.on('mousemove', function(date){
d3.select('line.tooltip')
.attr('transform', 'translate('+xScale(date)+',0)')
alphaWrap.select('text.tooltip')
.attr('transform', function(d,i){
var value = bisector(d.data, date);
return 'translate('+xScale(date)+','+scales[d.name](d.data[value].value)+')';
})
.text(function(d,i){
var value = bisector(d.data, date);
return d3.format('2.2f')(d.data[value].value);
});
});
关于javascript - 将 D3 中的条形图更改为折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45842149/