How to append multiple rectangles in d3.js?

Member

by larissa , in category: Javascript , 5 months ago

How to append multiple rectangles in d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 5 months ago

@larissa 

To append multiple rectangles in d3.js, you can use the .selectAll() and .data() methods to bind data to a selection of elements and then append rectangles based on that data. Here is an example code snippet that demonstrates how to append multiple rectangles in d3.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Sample data for rectangles
var data = [
  { x: 10, y: 20, width: 50, height: 30 },
  { x: 100, y: 50, width: 40, height: 20 },
  { x: 200, y: 80, width: 60, height: 40 }
];

// Create an SVG element
var svg = d3.select("body").append("svg")
    .attr("width", 400)
    .attr("height", 200);

// Bind data to rectangles and append rectangles
var rectangles = svg.selectAll("rect")
    .data(data)
    .enter()
    .append("rect")
    .attr("x", function(d) { return d.x; })
    .attr("y", function(d) { return d.y; })
    .attr("width", function(d) { return d.width; })
    .attr("height", function(d) { return d.height; })
    .attr("fill", "steelblue");


In this code snippet, we first define an array of data objects representing the rectangles we want to create. We then create an SVG element and bind the data to a selection of rectangles using the .selectAll(), .data(), and .enter() methods. Finally, we append rectangles to the SVG element using the .append("rect") method and set the position, size, and fill color of each rectangle based on the data.


Run this code in an HTML file with d3.js loaded, and you should see multiple rectangles displayed on the webpage.