使用 D3.js 时如何在热图顶部添加文本以正确显示每个矩形的值?

How to add text on top the heatmap to properly show value for each rectangle when using D3.js?

我的问题:我想在下面的热图的每个正方形顶部添加值文本,以便读者可以清楚地知道值到底是什么。我应该对以下代码进行哪些更改。

完整代码在这里https://www.d3-graph-gallery.com/graph/heatmap_style.html

希望有人能帮我解答这个问题。欣赏。

  svg.selectAll()
.data(data, function(d) {return d.group+':'+d.variable;})
.enter()
.append("rect")
  .attr("x", function(d) { return x(d.group) })
  .attr("y", function(d) { return y(d.variable) })
  .attr("rx", 4)
  .attr("ry", 4)
  .attr("width", x.bandwidth() )
  .attr("height", y.bandwidth() )
  .style("fill", function(d) { return myColor(d.value)} )
  .style("stroke-width", 4)
  .style("stroke", "none")
  .style("opacity", 0.8)
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseleave", mouseleave)

})

IIUC 您可以通过将以下代码添加到 .js 文件

来完成

完整代码在这里https://codepen.io/mohan-ys/pen/rNwgpmJ

var bar = svg
    .selectAll(".label")
    .data(data)
    .enter()
    .append("g")
    .attr("class", "label")
    .attr("transform", "translate(10,15)");
  bar
    .append("text")
    .attr("x", (d) => x(d.group))
    .attr("y", (d) => y(d.variable))
    .attr("dy", ".35em")
    .text((d) => d.value);