Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Creating a Simple Static Bar Chart with D3.js and SVG

Tech 2

This tutorial demonstrates how to build a basic bar chart visualization using D3.js and SVG elements within a static webpage.

HTML Structure

First, we set up the HTML page with a container for our chart.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Visualization Demo</title>
    <link rel="stylesheet" href="css/styles.css">
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
    <header>
        <h1>Data Visualization Example</h1>
    </header>
    <main>
        <section id="visualization-section">
            <h2>Bar Chart</h2>
            <p>A simple bar chart generated with D3.js.</p>
            <div id="chart-area"></div>
        </section>
    </main>
    <footer>
        <p>Static visualization example.</p>
    </footer>
    <script src="js/visualization.js"></script>
</body>
</html>

CSS Styling

Basic CSS is applied for layout and styling.

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    margin: 0;
    padding: 0;
}

header {
    background-color: #2c3e50;
    color: white;
    padding: 1rem;
    text-align: center;
}

main {
    padding: 2rem;
}

#chart-area {
    margin: 2rem auto;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 1rem;
    background-color: #f9f9f9;
}

footer {
    background-color: #2c3e50;
    color: white;
    text-align: center;
    padding: 1rem;
    position: fixed;
    bottom: 0;
    width: 100%;
}

JavaScript for D3.js Visualization

The core logic uses D3.js to bind data and draw SVG eelments.

// Sample dataset
const values = [15, 45, 22, 60, 35];

// Create the SVG canvas
const svgCanvas = d3.select('#chart-area')
    .append('svg')
    .attr('width', '100%')
    .attr('height', 350)
    .attr('viewBox', '0 0 500 350')
    .attr('preserveAspectRatio', 'xMidYMid meet');

// Draw the bars
svgCanvas.selectAll('.data-bar')
    .data(values)
    .enter()
    .append('rect')
    .attr('class', 'data-bar')
    .attr('x', (dataPoint, index) => index * 90 + 10)
    .attr('y', dataPoint => 340 - dataPoint * 4.5)
    .attr('width', 75)
    .attr('height', dataPoint => dataPoint * 4.5)
    .attr('fill', 'steelblue');

// Add value labels on top of bars
svgCanvas.selectAll('.data-label')
    .data(values)
    .enter()
    .append('text')
    .attr('class', 'data-label')
    .text(d => d)
    .attr('x', (d, i) => i * 90 + 47.5)
    .attr('y', d => 340 - d * 4.5 - 7)
    .attr('text-anchor', 'middle')
    .attr('fill', '#333')
    .style('font-weight', 'bold');

Code Explanation

1. Data Definition

const values = [15, 45, 22, 60, 35]; This array holds the numerical values that determine the height of each bar in the chart.

2. SVG Canvas Creation

  • d3.select('#chart-area') selects the HTML container div.
  • .append('svg') adds an SVG element inside the container.
  • The .attr() methods set the dimensions and scaling properties of the SVG. The viewBox defines the internal coordinate system, and preserveAspectRatio ensures the content scales proportional and remains centered.

3. Drawing the Bars

  • svgCanvas.selectAll('.data-bar').data(values) performs a data join, binding the dataset to placeholder selections for rectangle elements.
  • .enter() identifies data points with out corresponding DOM elements.
  • .append('rect') creates a new <rect> (rectangle) element for each new data point.
  • The subsqeuent .attr() calls position and size each bar:
    • x: Calculates the horizontal position based on the index.
    • y: Calculates the vertical position from the bottom of the SVG (coordinate 340) minus the bar height.
    • width and height: Define the bar dimensions.
    • fill: Sets the bar color.

4. Adding Data Labels

  • A similar data join process is used for text elements.
  • .text(d => d) sets the text content to the data value.
  • The x and y attributes position the text at the center-top of each bar.
  • text-anchor: 'middle' centers the text horizontally on its x-coordinate.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.