Building d3 heat map legend efficiently?

Hi fCC forum! I got my heat map to pass all of the tests but visually am really struggling with the legend (+ haven’t seen other posts on the forum that deal with it)!

Firstly, I should note that I’m using colors gleaned from fCC’s demo and that i have them all in a “color” object that looks like this:

const colors = [
  {
  "start": 11.7,
    "end": 12.8,
    "color": "d73027"
  },
  {
    "start": 10.6,
    "end": 11.7,
    "color": "F46D43"
  },

It’s like this but for 9 colors. My initial instinct was to make a legend in the same way that I made the original thing, something like:

d3.select("body")
.append("g")
.attr("id", "legend")
.selectAll("rect")
.data(colors)
.enter()
.append("rect")
.attr("x", (d, i) => { i * legendBarWidth})
.attr("width", legendBarWidth)
.attr("height", legendBarHeight)
.attr("fill", (d,i) => {return colors[i]["color"]})

This, of course, doesn’t work because I’m trying to selectAll “rects” when I do that far earlier in the code. I guess I’m wondering how I might add rects with fills and the labels in some sort of automated fashion rather than doing it manually. The current way I’m doing it accomplishes nothing/doesn’t show real data but just passes the test.

     d3.select("body")
       .append("h1")
       .attr("id", "title")
       .text("My Graph Title")
       .append("p")
       .attr("id", "description")
       .text("This is my heatmap!")
       .append("p")
       .text("Legend")
       .attr("id", "legend")
       .append("rect")
       .attr("height", 10) 
       .attr("width", 10)
       .attr("fill", colors[0]["color"])
       .append("rect")
       .attr("height", 10) 
       .attr("width", 10)
       .attr("fill", colors[1]["color"])
       .append("rect")
       .attr("height", 10) 
       .attr("width", 10)
       .attr("fill", colors[2]["color"])       
       .append("rect")
       .attr("height", 10) 
       .attr("width", 10)
       .attr("fill", colors[3]["color"])

This is a stupid implementation that passes the test but doesn’t actually fulfill the spirit of it. Would love some feedback/suggestions/ways of looking more at this!

Hi @lucasgelfond, do you have a Codepen or something with your code so far? Something to play around with :slight_smile:

Sorry for the late response and thank you again! Nice to see a familiar face on the forum :slight_smile:
Here’s my codepen!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.