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

Time:10-07

My question : I want to add value text on top of each square for the following heatmap so the readers can clearly know what exactly the value is. What changes should i make for the following code.

The full code is here https://www.d3-graph-gallery.com/graph/heatmap_style.html

Hope someone can help me with this question. Appreiate.

  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)

})

CodePudding user response:

IIUC You can do it with adding the below code to to you .js file

Complete code is here 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);
  • Related