重点代码块:
const svg: any = d3.select(this.$refs[ref])
.attr('width', this.width)
.attr('height', this.height);
svg.append('g')
.selectAll('rect')
.data(data)
.join('rect')
.attr('x', (d: any, i: number) => x(i))
.attr('y', (d: any) => y(d.value))
.attr('height', (d: any) => y(0) - y(d.value))
.attr('fill', (d: any, i: number) => {
if (difColor) {
return this.colorArr[i];
}
return this.colorArr[1];
})
.attr('width', x.bandwidth())
.on('mouseover', (data: any, index: any) => {
svg.append('text')
.attr('font-family', 'sans-serif')
.attr('font-size', 10)
.attr('text-anchor', 'middle')
.attr('class', 'divergence')
.attr('x', x(index)) // x轴对应的位置
.attr('y', y(data.value)) // y轴对应的位置
.attr('dx', '8px')
.text(data.value);
})
.on('mouseout', () => {
d3.selectAll('.divergence').remove();
});
参考地址:
https://wiki.jikexueyuan.com/project/d3wiki/interactive.html
https://observablehq.com/@d3/horizontal-bar-chart
https://observablehq.com/@d3/diverging-bar-chart