新闻中心

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

2025-10-14
浏览次数:
返回列表

使用 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 画布。

秀脸FacePlay 秀脸FacePlay

一款集成AI换脸、照片跳舞等多种AI特效玩法的App

秀脸FacePlay 124 查看详情 秀脸FacePlay
// 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 的数据绑定和动态更新机制,并将其应用到你的可视化项目中。

以上就是使用 D3.js 实现下拉菜单联动更新可视化图表的详细内容,更多请关注其它相关文章!


# 移除  # 抖音推广营销软件工作  # 如东硅基网站推广加盟  # 基础seo教程视频  # 湖北网站建设服务电话  # 北京专业抖音seo  # 河南营销推广摄影招聘网  # 澳门线上营销推广方案  # 谷歌seo专员  # 芜湖seo推广优质团队  # 农副产品网站推广怎么做  # 转换为  # 解决问题  # 中文网  # 相关文章  # 显示效果  # html  # 如何使用  # 运算符  # 绑定  # 创建一个  # red  # overflow  # 绘制图表  # ai  # access  # edge  # app  # svg  # node  # js 


相关栏目: 【 科技资讯46185 】 【 网络学院92790


相关推荐: mysql通配符支持数字匹配吗_mysql通配符能否用于数字匹配的解析  Web Components中自定义开关组件状态同步的常见陷阱与解决方案  Lar*el Form Request中唯一性验证在更新操作中的正确实现  飞书妙记怎样用语音转文字速记_飞书妙记用语音转文字速记【速记方法】  电脑屏幕颜色不舒服怎么办_Windows夜间模式与色彩校准教程【护眼技巧】  Django AJAX 文件上传教程:解决图片无法保存到模型的常见问题  Sublime怎么配置Nim语言环境_Sublime Nim代码高亮与补全  192.168.1.1管理中心入口 192.168.1.1路由器网页设置平台  AO3中文官网链接_AO3网页版稳定镜像站  CSS Box Model与弹性按钮:维持布局稳定的动画实践  腾讯QQ邮箱登录入口_QQ邮箱官方网站使用地址  新手怎么开始学化妆 零基础化妆入门教程  Golang如何处理RPC请求负载均衡_Golang RPC请求负载均衡策略与实践  深入理解J*aScript Promise异步执行与微任务队列  Windows电脑怎么截图最方便_系统自带截图工具的5种神仙用法【技巧】  漫蛙2漫画入口 漫蛙正版网页漫画直达网址  离线运行Go语言之旅:本地部署与GOPATH配置指南  Composer的 "licenses" 命令如何帮助你遵守开源协议_检查项目依赖的许可证合规性  MongoDB聚合管道:正确匹配对象数组中_id的方法  微信网页版官方入口直达 微信网页版网页版登录使用方法  铁路12306改签能改到更早的车次吗_铁路12306改签提前车次规则  PHP高效扁平化嵌套数组:使用array_merge与数组解包操作符  C++如何连接MySQL数据库_C++使用Connector/C++操作MySQL数据库教程  漫蛙2网页版漫画入口 漫蛙漫画在线官方登录  魅族17怎样用浏览器译外语网页_iPhone魅族17浏览器译外语网页【即时翻译】  Pygame教程:解决用户输入与游戏状态更新不同步问题  Odoo 16:在表单视图中基于当前记录动态修改Tree视图属性  LINUX的perf命令入门_LINUX官方性能分析工具的使用与解读  ACG动漫视频网入口 ACG动漫*免费正版观看地址  C++如何生成随机数_C++ random库使用方法与范围设置  Composer中的^和~符号代表什么_精通Composer版本号语义化约束  《刺客信条4:黑旗》重制版新细节曝光:无缝加载 地图更细致!  QQ邮箱网页版入口页面 QQ邮箱在线登录入口官网  Django表单提交验证失败后保持字段值不刷新  Composer如何处理Git子模块(submodule)依赖_Composer与Git Submodule的对比与选择  谷歌浏览器最新官方入口链接 谷歌浏览器网页版官网导航  顺丰快递查询系统 官方正版查询入口  Angular Material 垂直步进器:实现底部到顶部排序的教程  小米14应用无法联网原因分析_小米14网络权限修复  Golang如何优雅处理error_Golang error处理最佳实践总结  多闪网页版在线观看免费入口_多闪官网访问入口  深入理解与实现最大堆的Heapify过程:常见错误与修正  qq浏览器打开空白页怎么办 qq浏览器启动后显示白屏的解决教程  Python模块化编程:有效管理依赖与避免循环引用  快速CSGO开箱网站指南 CSGO开箱平台推荐  Go语言中对Map值调用带指针接收者方法:原理与最佳实践  在Qt QML中通过Python字典动态更新TextEdit内容的教程  必由学登录入口 必由学官方网站在线访问链接  抖音极速版最新版本 抖音极速版官方下载地址  J*aScript实现单选按钮与关联输入框的联动禁用教程 

搜索