首页 > 解决方案 > 在 d3.js 散点图中悬停在点上时显示图像

问题描述

我以前没有使用过 d3.js,我正在尝试创建一个散点图,将鼠标悬停在这些点上会显示图像本身(缩小到更小的尺寸)。

我看过一些教程,当鼠标指针悬停在点上时可以显示文本。例如,我查看了以下链接:12。我想做类似的事情,但是当我将鼠标悬停在该点上时会显示图像本身。

我也不确定是否要在本地文件夹中复制这些链接。考虑第一个链接1,我在本地创建了 index.html、serial.csv 和 scatter.css 文件并复制了给定的代码。然而,当我在浏览器中打开 index.html 时,我看到一个带有单个“xAxis”按钮的空白屏幕。index.html 文件似乎使用了该链接中不存在的 scatter.js 文件。不知道我可以从哪里得到它。我的意图是用图像标签替换文本。

有任何想法吗?

标签: imaged3.jsscatter-plot

解决方案


我建议您观看有关如何使用 d3 制作散点图的视频,尤其是因为您不熟悉它。我发现这个视频有助于制作散点图:

https://vizhub.com/curran/9247d4d42df74185980f7b1f7504dcc5

然后,要使用图像制作悬停效果,您需要使用Tooltip。您必须将它附加到构成散点图的所有圆圈,并将图像作为“背景图像”的属性。这方面的代码示例是:

let svg = d3.select('svg');

let tooltip = d3
    .select("body")
    .append("div")
       .attr("id", "tooltip")

svg.selectAll('circle')
    // Create scatterplot points from dataset
    .data(dataset)
    .enter()
    .append('circle')
        .attr('x', 'x-coord') // Location of circle on x-axis
        .attr('y', "y-coord") 
        .style('fill','#4aa89c')

        // Tooltip styling when mouse hovers over
        .on("mouseover", function (d, i) {
            d3.select(this).style("fill", "a8eddf");
            tooltip.attr("id", "tooltip")
            tooltip.style("fill", "#a8eddf")
            tooltip.attr("data-date", d[0])
            tooltip.style('background-image','url("image-url")')
            tooltip.style('background-size','cover')
            tooltip.style('opacity', 1)             
         })

        // Tooltip styling when mouse is off the point
        .on("mouseout", function () {
            d3.select(this)
                .transition()
                .duration(400)
                .style("fill", "#4aa89c");
            tooltip.style("opacity", 0);
        })

推荐阅读