Choropleth Map - Problem showing legend's text

Hello !

I have the Choropleth Map completed and with all tests passing, but I have a problem with the legend part which I can’t resolve.

I’m able to show the legend’s colors, but I can’t find the way to show the corresponding text next to each color.

Here is my legend’s code:

const colors = [
  {
    "color": "#ffcccc",
    "text": "Less than 15%"
  }, 
  {
    "color": "#ff8080",
    "text": "Less than 30%"
  },
  {
    "color": "#ff0000",
    "text": "Less than 45%"
  },
  {
    "color": "#990000",
    "text": "More than 45%"
  }
]

const legendWidth = 220
const legendHeight = 120

const legendRectWidth = 30
const legendRectHeight = legendHeight / colors.length

let legend = d3.select("#legend")
  .attr("width", legendWidth)
  .attr("height", legendHeight)
  .selectAll("rect")
  .data(colors)
  .enter()
  .append("rect")
  .attr("fill", (c, i) => colors[i].color)
  .attr("x", 0)
  .attr("y", (c, i) => legendRectHeight * i)
  .attr("width", legendRectWidth)
  .attr("height", legendRectHeight)  

legend.selectAll("text")
  .data(colors)
  .enter()
  .append("text")
  .attr("fill", "black")
  .attr("x", legendRectWidth + 10)
  .attr("y", (c, i) => legendRectHeight * i)
  .text((c, i) => colors[i].text)
  .style("font-size", "12px")
  .attr("alignment-baseline","middle")

And, also, the link to the project: https://codepen.io/pedrorv1998/pen/BaLvqez?editors=0010

I appreciate any help!

When you first define the legend in JavaScript write:

let legend = d3.select("#legend")

legend
.attr(“width”, legendWidth)
.attr(“height”, legendHeight)

instead of

let legend = d3.select("#legend")
.attr(“width”, legendWidth)
.attr(“height”, legendHeight)

This should solve the issue.

I am sure there is a good way to explain, why this is… I currently don’t know it :smiley:

Welcome, Pedro.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Okay. It was my first post and I didn’t know. I will take this into consideration from now on. Thanks!

Yes, it works!! I spent a lot of time and it was just this… It’s a strange issue, not intuitive at all.

I’m happy it’s working now. Thanks!