1

我正在处理 D3 中的热图图表,但我不知道如何在鼠标悬停时添加文本。我不确定如何进行。如果你能给我一些线索,我将不胜感激。在以下代码段中,您可以找到代码。工作和非工作代码块。谢谢!


console.log(d3)

let screenWidth = 800
let screenHeight = 400

//load data
d3.csv('./datos/locations.csv').then(function(data){
    let filtered = []
    for(let item of data) {
        if(item.location === "location one") {
            filtered.push(item)
        }
    }

    build(filtered)
})

//Create canvas
function createSVG() {
    let container = d3.select('#container')
    svg = container.append('svg')
    .attr('id', 'canvas')
    .attr('width', screenWidth)
    .attr('height', screenHeight)
}

//Create chart
function build(data) {

    let rectWidth = screenWidth / 24
    let rectHeight = screenHeight / 7

    let rects = svg.selectAll('rect')
      .data(data)
      .enter()
      .append('rect')
        .attr('x', function(d,i) {
            return (parseInt(d.hour) - 1) * rectWidth})
        .attr('y', function(d,i){
            return (parseInt(d.day) - 1) * rectHeight})  
        .attr('height', rectHeight) 
        .attr('width', rectWidth)
        .style('fill', 'black')
        .style('stroke', 'white')
        .on('mouseover', function(d,i) {
            let rects = d3.select(this)
            .append('text')
            .attr('x')
            .attr('y')
            .style('font-weight', 500)
            .style('font-family', 'Arial')
            .style('fill', 'red')
            .text(function (d,i) {return d.value})})
        }

function main() {
    createSVG()
    build()
}

main()
```
4

2 回答 2

0

<text>节点不能是<rect>s 的子节点,就像<line>s 或<circle>s 不能一样。它们是图形节点,并不意味着有孩子。将工具提示附加到 SVG 或<g>代替。

这意味着您无法再d.value通过 the访问function (d,i) {return d.value}),但您可以获取它,因为您可以访问dfrom .on('mouseover', function(d,i) {,只需删除除d.value.

如果你使用xand yfrom <rect>,将会发生的事情是<text>元素覆盖,捕获鼠标事件并立即在 上<rect>触发。由于您可能希望删除 上的工具提示,因此文本节点会闪烁。将文本至少向右移动或使用获取事件的鼠标坐标并将其稍微向下和向右移动,使用类似向右移动的方式。mouseout<rect>mouseoutrectWidthd3.event.attr('x', d3.event.clientX + 10)

于 2020-11-02T20:00:24.863 回答
0

您可以将<div>with附加position: absolute到 body 并将其定位在 mousemove 事件上。更改不透明度以更新其显示或隐藏。

var div = d3.select('body').append('div')   
    .attr('class', 'tooltip')               
    .style('opacity', 0);

...
.on('mouseover', function(d) {      
    div.transition()        
        .duration(200)      
        .style('opacity', .9);      
    div.html('<h3>' + d.status + '</h3>' + '<p>' + timeFormat(new Date(d.date)) + ' at ' + monthDayFormat(new Date(d.date)) + '</p>')  
        .style('left', (d3.event.pageX) + 'px')     
        .style('top', (d3.event.pageY - 28) + 'px');    
    })   

https://jsfiddle.net/z9ucLqu2/

于 2020-11-03T01:53:05.127 回答