1

I have this code snippet where I'm using D3.js to create a 1 column grid with colors given by an array of hex codes. I've set the y position of each rect element to be i*height (where i is the index of the color hex code). In the output I can see the rect elements but the last one (red in color) is invisible.

When I inspect my HTML I can see that it's where I need it to be, it's just invisible. How do I adjust my code to make the last rect visible?

let colors=['#2A4DE8','#2AA3E8', '#F6922E','#F62E2E'];


let legend=d3.select('#legend');

legend.selectAll('rect')
      .data(colors)
      .enter()
      .append('rect')
      .attr('fill', (color)=>{return color})
      .attr('width', '50px')
      .attr('height', '50px')
      .attr('x', '0px')
      .attr('y', (color,index)=>{return index*50})
    
      
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>

<svg id="legend"></svg>
LindaniB
  • 53
  • 5

1 Answers1

0

I changed let legend=d3.select('#legend'); to let legend=d3.select('#legend').attr("height", "200px"); in order to overrided the default svg height of 150px.

[see https://stackoverflow.com/a/40156993/5768908 ]

let colors=['#2A4DE8','#2AA3E8', '#F6922E','#F62E2E'];


let legend=d3.select('#legend').attr("height", "200px");

legend.selectAll('rect')
      .data(colors)
      .enter()
      .append('rect')
      .attr('fill', (color)=>{return color})
      .attr('width', '50px')
      .attr('height', '50px')
      .attr('x', '0px')
      .attr('y', (color,index)=>{return index*50})
    
      
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>

<svg id="legend">
       
</svg>
LindaniB
  • 53
  • 5