0

0

使用 D3.js 实现下拉菜单联动更新可视化图表

碧海醫心

碧海醫心

发布时间:2025-10-14 11:35:24

|

418人浏览过

|

来源于php中文网

原创

使用 d3.js 实现下拉菜单联动更新可视化图表

本文档将指导你如何使用 D3.js 创建一个动态图表,该图表能够根据 HTML 下拉菜单的选择进行数据更新。我们将重点讲解如何监听下拉菜单的 `change` 事件,并利用 D3.js 的 `join`, `enter`, `update`, `exit` 模式高效地更新图表元素,实现数据驱动视图的动态变化。

教程内容

1. 数据准备

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

// desired permutation length
const length = 4;

// build array from the above length
const perm = Array.from(Array(length).keys()).map((d) => d + 1);

// generate corresponding alphabets for name
const name = perm.map((x) => String.fromCharCode(x - 1 + 65));

// permutation function
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;
};

// generate permutations
const permut = permute(perm);

// generate year based on permutation
const year = permut.map((x, i) => i + 2000);

// generate a yearly constant based on year to generate final value as per the rank {year-name}
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();

2. 创建 HTML 下拉菜单

接下来,我们使用 D3.js 在 HTML 页面中创建一个下拉菜单。该下拉菜单将包含数据集 src 中的所有年份选项。

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)

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

为了使图表能够根据下拉菜单的选择进行更新,我们需要监听下拉菜单的 change 事件。当用户选择不同的年份时,我们将获取选中的年份值,并调用 draw() 函数来更新图表。

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

注意:

  • 使用 event.currentTarget.value 获取选中的年份值。
  • 使用 + 运算符将年份值转换为数字类型。
  • 将选中的年份值作为参数传递给 draw() 函数。

4. 创建 SVG 画布

绘制图表之前,我们需要创建一个 SVG 画布。

灵机语音
灵机语音

灵机语音

下载
// namespace
// define dimension
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")
    .style("overflow", "visible")
    .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; //controls the height of the visual container
const multiplierW = 1; //controls the width of the visual container

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

//create BOUND rect -- to be deleted later
svg
    .append("rect")
    .attr("class", "boundRect")
    .attr("x", `${padding.left}`)
    .attr("y", `${padding.top}`)
    .attr("width", `${boundWidth}`)
    .attr("height", `${boundHeight}`)
    .attr("fill", "white");

//create bound element
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);

5. 绘制图表

draw() 函数负责根据选中的年份值过滤数据,并使用 D3.js 的 join, enter, update, exit 模式更新图表元素。

function draw(filterYr) {
    // filter data as per dropdown
    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
                        .style("fill", "black")
                        .transition()
                        .duration(1000)
                        .attr("transform", (d, i) => `translate(${300},${30 + i * 30})`)
                        .remove()*/
        )
}

draw(filterYr);

代码解释:

  • data(data): 将过滤后的数据绑定到 SVG 元素。
  • join(enter, update, exit): D3.js 的核心方法,用于处理数据的 enter, update 和 exit 状态。
    • enter: 处理新增的数据,创建新的 SVG 元素。
    • update: 处理已存在的数据,更新 SVG 元素的属性。
    • exit: 处理被移除的数据,移除对应的 SVG 元素。
  • .transition().duration(500): 为更新操作添加过渡效果,使图表变化更加平滑。

完整代码

<!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>D3.js Dropdown Update</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>

<body>
    <svg></svg>
    <script>
        // desired permutation length
        const length = 4;

        // build array from the above length
        const perm = Array.from(Array(length).keys()).map((d) => d + 1);

        // generate corresponding alphabets for name
        const name = perm.map((x) => String.fromCharCode(x - 1 + 65));

        // permutation function
        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;
        };

        // generate permutations
        const permut = permute(perm);

        // generate year based on permutation
        const year = permut.map((x, i) => i + 2000);

        // generate a yearly constant based on year to generate final value as per the rank {year-name}
        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();

        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)

        //get the dropdown value
        const filterYr = parseFloat(d3.select('.Year').node().value);

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

        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")
            .style("overflow", "visible")
            .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; //controls the height of the visual container
        const multiplierW = 1; //controls the width of the visual container

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

        //create BOUND rect -- to be deleted later
        svg
            .append("rect")
            .attr("class", "boundRect")
            .attr("x", `${padding.left}`)
            .attr("y", `${padding.top}`)
            .attr("width", `${boundWidth}`)
            .attr("height", `${boundHeight}`)
            .attr("fill", "white");

        //create bound element
        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);


        function draw(filterYr) {

            // filter data as per dropdown
            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
                                .style("fill", "black")
                                .transition()
                                .duration(1000)
                                .attr("transform", (d, i) => `translate(${300},${30 + i * 30})`)
                                .remove()*/
                )
        }

        draw(filterYr);
    </script>
</body>

</html>

总结

通过本教程,你学习了如何使用 D3.js 创建一个能够根据 HTML 下拉菜单的选择进行动态更新的图表。 关键步骤包括:

  1. 创建下拉菜单: 使用 D3.js 创建 HTML 下拉菜单,并绑定年份数据。
  2. 监听 change 事件: 监听下拉菜单的 change 事件,获取选中的年份值。
  3. 数据过滤: 根据选中的年份值过滤数据集。
  4. 绘制图表: 使用 D3.js 的 join, enter, update, exit 模式更新图表元素。

希望本教程能够帮助你更好地理解 D3.js 的数据绑定和动态更新机制,并将其应用到你的可视化项目中。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1570

2023.10.24

Go语言中的运算符有哪些
Go语言中的运算符有哪些

Go语言中的运算符有:1、加法运算符;2、减法运算符;3、乘法运算符;4、除法运算符;5、取余运算符;6、比较运算符;7、位运算符;8、按位与运算符;9、按位或运算符;10、按位异或运算符等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

241

2024.02.23

php三元运算符用法
php三元运算符用法

本专题整合了php三元运算符相关教程,阅读专题下面的文章了解更多详细内容。

170

2025.10.17

js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

531

2023.06.20

js获取当前时间
js获取当前时间

JS全称JavaScript,是一种具有函数优先的轻量级,解释型或即时编译型的编程语言;它是一种属于网络的高级脚本语言,主要用于Web,常用来为网页添加各式各样的动态功能。js怎么获取当前时间呢?php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

576

2023.07.28

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

761

2023.08.03

js是什么意思
js是什么意思

JS是JavaScript的缩写,它是一种广泛应用于网页开发的脚本语言。JavaScript是一种解释性的、基于对象和事件驱动的编程语言,通常用于为网页增加交互性和动态性。它可以在网页上实现复杂的功能和效果,如表单验证、页面元素操作、动画效果、数据交互等。

6305

2023.08.17

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

494

2023.09.01

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

69

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.6万人学习

AngularJS教程
AngularJS教程

共24课时 | 4.2万人学习

CSS教程
CSS教程

共754课时 | 43.5万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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