This code creates a simple bar chart using the D3.js...

August 29, 2025 at 04:45 AM

<!DOCTYPE html> <html> <head> <script src="https://d3js.org/d3.v7.min.js"></script> </head> <body> <script> const data = [10, 20, 30, 40, 50]; const width = 500; const height = 200; const svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); svg.selectAll("rect") .data(data) .enter() .append("rect") .attr("x", (d, i) => i * 50) .attr("y", d => height - d * 4) .attr("width", 40) .attr("height", d => d * 4) .attr("fill", "teal"); </script> </body> </html>

This code creates a simple bar chart using the D3.js (Data-Driven Documents) library. Here's a detailed breakdown of what each part of the code does:

  1. Data Initialization:

    const data = [10, 20, 30, 40, 50];
    
    • An array of numerical data is created, which represents the values of the bars in the chart.
  2. SVG Canvas Setup:

    const width = 500;
    const height = 200;
    const svg = d3.select("body")
                  .append("svg")
                  .attr("width", width)
                  .attr("height", height);
    
    • An SVG (Scalable Vector Graphics) element is created and added to the <body> of the HTML document.
    • The svg element has a defined width of 500 pixels and height of 200 pixels, which serves as the canvas for drawing graphics.
  3. Bar Creation:

    svg.selectAll("rect")
       .data(data)
       .enter()
       .append("rect")
       .attr("x", (d, i) => i * 50)
       .attr("y", d => height - d * 4)
       .attr("width", 40)
       .attr("height", d => d * 4)
       .attr("fill", "teal");
    
    • svg.selectAll("rect"): Selects all rect elements within the svg (none exist initially).
    • .data(data): Binds the data array to the selection.
    • .enter(): Adds new elements to match the data.
    • .append("rect"): Appends a rectangle (<rect>) for each data point.
    • .attr("x", (d, i) => i * 50): Sets the x-coordinate of each rectangle. The i (index) is multiplied by 50 to space the bars evenly.
    • .attr("y", d => height - d * 4): Positions the top of the rectangle based on the value d (the data value), scaled by 4. The subtraction from height ensures the bars grow upward instead of downward.
    • .attr("width", 40): Sets the width of each rectangle to 40 pixels.
    • .attr("height", d => d * 4): Sets the height of each rectangle based on the data value, scaled by 4.
    • .attr("fill", "teal"): Fills the bars with a teal color.

Result:

  • A bar chart with 5 bars will be displayed.
  • The height of each bar corresponds to the value in the data array, scaled by 4.
  • The bars are spaced 50 pixels apart horizontally, with each bar being 40 pixels wide.
  • The bars are colored teal.
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node