使用 D3.js 实现基于下拉菜单的动态数据更新

霞舞
发布: 2025-10-14 11:34:13
原创
550人浏览过

使用 d3.js 实现基于下拉菜单的动态数据更新

本文档旨在指导开发者如何使用 D3.js 结合 HTML 下拉菜单(`

1. 数据准备

首先,我们需要准备用于生成图表的数据。以下代码生成一个包含年份、名称、排名和数值的示例数据集。

// 期望的排列长度
const length = 4;

// 从上述长度构建数组
const perm = Array.from(Array(length).keys()).map((d) => d + 1);

// 为名称生成对应的字母
const name = perm.map((x) => String.fromCharCode(x - 1 + 65));

// 排列函数
function permute(permutation) {
    var length = permutation.length,
        result = [permutation.slice()],
        c = new Array(length).fill(0),
        i = 1,
        k, p;

    while (i < length) {
        if (c[i] < i) {
            k = i % 2 && c[i];
            p = permutation[i];
            permutation[i] = permutation[k];
            permutation[k] = p;
            ++c[i];
            i = 1;
            result.push(permutation.slice());
        } else {
            c[i] = 0;
            ++i;
        }
    }
    return result;
};

// 生成排列
const permut = permute(perm);

// 基于排列生成年份
const year = permut.map((x, i) => i + 2000);

// 基于年份生成年度常量,用于生成最终值
const constant = year.map(d => Math.round(d * Math.random()));

const src =
    year.map((y, i) => {
        return name.map((d, j) => {
            return {
                Name: d,
                Year: y,
                Rank: permut[i][j],
                Const: constant[i],
                Value: Math.round(constant[i] / permut[i][j])
            };
        });
    }).flat();
登录后复制

这段代码生成一个名为 src 的数组,其中包含了后续图表需要用到的数据。

2. 构建 HTML 下拉菜单

接下来,我们需要在 HTML 中创建一个下拉菜单,用于选择年份。

const select = d3.select('body')
    .append('div', 'dropdown')
    .style('position', 'absolute')
    .style('top', '400px')
    .append('select')
    .attr('name', 'input')
    .classed('Year', true);

select.selectAll('option')
    .data(year)
    .enter()
    .append('option')
    .text((d) => d)
    .attr("value", (d) => d)
登录后复制

这段代码使用 D3.js 创建一个 select 元素,并使用 year 数组填充下拉菜单的选项。每个选项的文本和值都设置为对应的年份。

3. 监听下拉菜单的 change 事件

关键在于监听下拉菜单的 change 事件,并在事件触发时更新图表。

select.on("change", event => {
    const filterYr = +event.currentTarget.value;
    draw(filterYr);
});
登录后复制

这段代码监听 select 元素的 change 事件。当用户选择不同的年份时,event.currentTarget.value 获取选中的年份值,并将其传递给 draw() 函数。注意,这里使用了 + 运算符将字符串转换为数字。

4. 创建 SVG 元素和坐标轴

在 draw() 函数之外,我们需要创建 SVG 元素和坐标轴。

// 定义维度
const width = 1536;
const height = 720;
const svgns = "http://www.w3.org/2000/svg";
const svg = d3.select("svg");

svg.attr("xmlns", svgns).attr("viewBox", `0 0 ${width} ${height}`);

svg
    .append("rect")
    .attr("class", "vBoxRect")
    .attr("width", `${width}`)
    .attr("height", `${height}`)
    .attr("stroke", "black")
    .attr("fill", "white");

const padding = {
    top: 70,
    bottom: 100,
    left: 120,
    right: 120
};
const multiplierH = 1;
const multiplierW = 1;

const boundHeight = height * multiplierH - padding.top - padding.bottom;
const boundWidth = width * multiplierW - padding.right - padding.left;

const bound = svg
    .append("g")
    .attr("class", "bound")
    .style("transform", `translate(${padding.left}px,${padding.top}px)`);

const g = bound.append('g')
    .classed('textContainer', true);
登录后复制

这段代码创建了一个 SVG 元素,并定义了图表的尺寸和边距。同时,创建了一个 g 元素,用于存放后续的数据可视化元素。 注意:g 元素应该在 draw() 函数之外创建,否则每次调用 draw() 函数都会创建一个新的 g 元素,导致图表元素重复添加。

腾讯智影-AI数字人
腾讯智影-AI数字人

基于AI数字人能力,实现7*24小时AI数字人直播带货,低成本实现直播业务快速增增,全天智能在线直播

腾讯智影-AI数字人 73
查看详情 腾讯智影-AI数字人

5. 实现 draw() 函数

draw() 函数负责根据选定的年份过滤数据,并更新图表。

function draw(filterYr) {
    // 过滤数据
    const data = src.filter(a => a.Year == filterYr);

    // 创建比例尺
    const xAccessor = (d) => d.Year;
    const yAccessor = (d) => d.Value;

    const scaleX = d3
        .scaleLinear()
        .range([0, boundWidth])
        .domain(d3.extent(data, xAccessor));

    const scaleY = d3
        .scaleLinear()
        .range([boundHeight, 0])
        .domain(d3.extent(data, yAccessor));

    g.selectAll('text')
        .data(data)
        .join(
            enter => enter.append('text')
            .attr('x', (d, i) => scaleX(d.Year))
            .attr('y', (d, i) => i)
            .attr('dy', (d, i) => i * 30)
            .text((d) => d.Year + '-------' + d.Value.toLocaleString())
            .style("fill", "blue"),
            update =>
            update
            .transition()
            .duration(500)
            .attr('x', (d, i) => scaleX(d.Year))
            .attr('y', (d, i) => i)
            .attr('dy', (d, i) => i * 30)
            .text((d) => d.Year + '-------' + d.Value.toLocaleString())
            .style("fill", "red"),
            exit => exit.remove() // 添加 exit 选择,移除不再需要的元素
        );
}
登录后复制

这段代码首先根据 filterYr 过滤数据。然后,创建 x 和 y 轴的比例尺。最后,使用 D3.js 的 join 方法,根据过滤后的数据更新 text 元素。enter 选择用于创建新的 text 元素,update 选择用于更新已存在的 text 元素,exit 选择用于移除不再需要的元素。

注意:

  • 确保在 join 方法中添加 exit 选择,以便在数据更新时移除不再需要的元素,避免图表元素堆积。
  • 比例尺的定义需要放在 draw 函数内部,因为数据变化后,比例尺的 domain 也会发生变化。

6. 初始调用 draw() 函数

最后,需要在页面加载时调用一次 draw() 函数,以便显示初始数据。

draw(filterYr);
登录后复制

这段代码在页面加载时调用 draw() 函数,并传入初始的 filterYr 值。

7. 完整代码示例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>

<body>
    <svg></svg>

    <script>
        // 数据准备(与前面相同)
        const length = 4;
        const perm = Array.from(Array(length).keys()).map((d) => d + 1);
        const name = perm.map((x) => String.fromCharCode(x - 1 + 65));

        function permute(permutation) {
            var length = permutation.length,
                result = [permutation.slice()],
                c = new Array(length).fill(0),
                i = 1,
                k, p;

            while (i < length) {
                if (c[i] < i) {
                    k = i % 2 && c[i];
                    p = permutation[i];
                    permutation[i] = permutation[k];
                    permutation[k] = p;
                    ++c[i];
                    i = 1;
                    result.push(permutation.slice());
                } else {
                    c[i] = 0;
                    ++i;
                }
            }
            return result;
        };

        const permut = permute(perm);
        const year = permut.map((x, i) => i + 2000);
        const constant = year.map(d => Math.round(d * Math.random()));

        const src =
            year.map((y, i) => {
                return name.map((d, j) => {
                    return {
                        Name: d,
                        Year: y,
                        Rank: permut[i][j],
                        Const: constant[i],
                        Value: Math.round(constant[i] / permut[i][j])
                    };
                });
            }).flat();

        // 构建 HTML 下拉菜单
        const select = d3.select('body')
            .append('div', 'dropdown')
            .style('position', 'absolute')
            .style('top', '400px')
            .append('select')
            .attr('name', 'input')
            .classed('Year', true);

        select.selectAll('option')
            .data(year)
            .enter()
            .append('option')
            .text((d) => d)
            .attr("value", (d) => d);

        // 获取初始下拉菜单值
        const filterYr = parseFloat(d3.select('.Year').node().value);

        // 监听下拉菜单的 `change` 事件
        select.on("change", event => {
            const filterYr = +event.currentTarget.value;
            draw(filterYr);
        });

        // 创建 SVG 元素和坐标轴
        const width = 1536;
        const height = 720;
        const svgns = "http://www.w3.org/2000/svg";
        const svg = d3.select("svg");

        svg.attr("xmlns", svgns).attr("viewBox", `0 0 ${width} ${height}`);

        svg
            .append("rect")
            .attr("class", "vBoxRect")
            .attr("width", `${width}`)
            .attr("height", `${height}`)
            .attr("stroke", "black")
            .attr("fill", "white");

        const padding = {
            top: 70,
            bottom: 100,
            left: 120,
            right: 120
        };
        const multiplierH = 1;
        const multiplierW = 1;

        const boundHeight = height * multiplierH - padding.top - padding.bottom;
        const boundWidth = width * multiplierW - padding.right - padding.left;

        const bound = svg
            .append("g")
            .attr("class", "bound")
            .style("transform", `translate(${padding.left}px,${padding.top}px)`);

        const g = bound.append('g')
            .classed('textContainer', true);

        // 实现 `draw()` 函数
        function draw(filterYr) {
            const data = src.filter(a => a.Year == filterYr);

            const xAccessor = (d) => d.Year;
            const yAccessor = (d) => d.Value;

            const scaleX = d3
                .scaleLinear()
                .range([0, boundWidth])
                .domain(d3.extent(data, xAccessor));

            const scaleY = d3
                .scaleLinear()
                .range([boundHeight, 0])
                .domain(d3.extent(data, yAccessor));

            g.selectAll('text')
                .data(data)
                .join(
                    enter => enter.append('text')
                    .attr('x', (d, i) => scaleX(d.Year))
                    .attr('y', (d, i) => i)
                    .attr('dy', (d, i) => i * 30)
                    .text((d) => d.Year + '-------' + d.Value.toLocaleString())
                    .style("fill", "blue"),
                    update =>
                    update
                    .transition()
                    .duration(500)
                    .attr('x', (d, i) => scaleX(d.Year))
                    .attr('y', (d, i) => i)
                    .attr('dy', (d, i) => i * 30)
                    .text((d) => d.Year + '-------' + d.Value.toLocaleString())
                    .style("fill", "red"),
                    exit => exit.remove()
                );
        }

        // 初始调用 `draw()` 函数
        draw(filterYr);
    </script>
</body>

</html>
登录后复制

8. 总结

通过以上步骤,我们成功地使用 D3.js 和 HTML 下拉菜单实现了动态数据更新。 关键点包括:

  • 监听下拉菜单的 change 事件。
  • 在 draw() 函数中过滤数据。
  • 使用 D3.js 的 join, enter, update, exit 模式更新图表。
  • 确保在 join 方法中添加 exit 选择,避免图表元素堆积。
  • 在 draw 函数之外创建 g 元素。

掌握这些技术,可以为用户提供更加交互性强、动态的可视化体验。

以上就是使用 D3.js 实现基于下拉菜单的动态数据更新的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号