首页 > 解决方案 > 以编程方式将样式添加到 D3 热图的列

问题描述

我从这里得到了一个基本的热图。

现在我希望能够突出显示绘图的一整列,例如围绕所有值绘制一个矩形(也可以更简单一些):

在此处输入图像描述

我还使用 react 来跟踪应该突出显示哪一列。因此,我需要能够以编程方式更改此突出显示而无需任何鼠标操作。

有谁知道如何在不使用鼠标事件的情况下设置整个列的样式?这甚至可能吗?

标签: javascriptreactjsd3.js

解决方案


您可以在创建热图时附加突出显示元素,并在变量更改时更新突出显示元素的位置/不透明度。

请注意,您还需要将 d3 比例函数存储在变量中。

const svg = "however you're selecting the svg here"

svg.append('rect')
    .attr("id", "highlight")
    .attr("width", xScale.bandwidth())
    .attr("height", 'height of the heatmap')
    .attr("x", 0)
    .attr("y", 0)
    .attr("opacity", 0)
    .attr("stroke", '#ffffff')
    .attr("stroke-width", 2)

当以编程方式更改变量时,使用 d3 选择该元素并更新其位置

function changePosition(column) {
    const svg = "however you're selecting the svg here"
    const xScale = "that variable where you put the xScale function when you appended your heatmap"

    svg.select("#highlight")
        .attr("x", xScale(column))
        .attr("opacity", 1)
}

推荐阅读