d3 demo

by Evgeniy Lukovsky

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>D3.js Dynamic Filtering</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <style>
        .bar {
            fill: steelblue;
        }
        .bar:hover {
            fill: orange;
        }
        .axis-label {
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div>
        <label for="category-filter">Filter by Category:</label>
        <select id="category-filter">
            <option value="all">All</option>
            <option value="category1">Category 1</option>
            <option value="category2">Category 2</option>
        </select>
    </div>
    <svg width="800" height="400"></svg>
    <script src="app.js"></script>
</body>
</html>

JavaScript

// Sample data
const data = [
    { category: 'category1', value: 30 },
    { category: 'category1', value: 80 },
    { category: 'category2', value: 45 },
    { category: 'category2', value: 60 },
    { category: 'category1', value: 20 },
    { category: 'category2', value: 90 },
    { category: 'category1', value: 50 },
    { category: 'category2', value: 70 }
];

// Set up SVG dimensions
const svg = d3.select("svg"),
    margin = { top: 20, right: 30, bottom: 40, left: 40 },
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom;

const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);

// Set up scales
const x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
const y = d3.scaleLinear().rangeRound([height, 0]);

// Set up axes
const xAxis = g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", `translate(0,${height})`);

const yAxis = g.append("g")
    .attr("class", "axis axis--y");

// Function to update the chart
function update(data) {
    x.domain(data.map(d => d.category));
    y.domain([0, d3.max(data, d => d.value)]);

    xAxis.call(d3.axisBottom(x));
    yAxis.call(d3.axisLeft(y));

    const bars = g.selectAll(".bar")
        .data(data, d => d.category + d.value);

    bars.exit().remove();

    bars.enter().append("rect")
        .attr("class", "bar")
        .attr("x", d => x(d.category))
        .attr("y", d => y(d.value))
        .attr("width", x.bandwidth())
        .attr("height", d => height - y(d.value))
        .merge(bars)
        .transition()
        .duration(750)
        .attr("x", d => x(d.category))
        .attr("y", d => y(d.value))
        .attr("width", x.bandwidth())
        .attr("height", d => height - y(d.value));
}

// Initial rendering
update(data);

// Event listener for the filter
d3.select("#category-filter").on("change", function() {
    const selectedCategory = d3.select(this).property("value");
  ...