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

碧海醫心
发布: 2025-10-14 11:35:24
原创
408人浏览过

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

爱图表
爱图表

AI驱动的智能化图表创作平台

爱图表 99
查看详情 爱图表
// 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 实现下拉菜单联动更新可视化图表的详细内容,更多请关注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号