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

花韻仙語
发布: 2025-10-15 10:16:37
原创
134人浏览过

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

本文档将指导你如何使用D3.js构建一个动态图表,该图表的数据会根据HTML下拉菜单的选择进行更新。我们将重点讲解如何监听下拉菜单的`change`事件,以及如何利用D3的`join`、`enter`、`update`模式来实现数据的动态更新。通过本文,你将学会如何将用户交互与D3.js的数据可视化结合起来,创建更具交互性的Web应用。

1. 准备工作

首先,确保你已经引入了D3.js库。你可以通过以下方式在HTML文件中引入:

<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
登录后复制

2. 数据准备

我们需要一些数据来生成图表,并且这些数据需要能够根据下拉菜单的选择进行过滤。以下是一个示例数据生成代码:

// 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();
登录后复制

这段代码生成一个名为src的数据集,其中包含年份、名称、排序和值等信息。

3. 创建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创建了一个下拉菜单,并将年份数据绑定到下拉菜单的选项中。

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

现在,我们需要监听下拉菜单的change事件,以便在用户选择不同的年份时更新图表。

怪兽AI数字人
怪兽AI数字人

数字人短视频创作,数字人直播,实时驱动数字人

怪兽AI数字人 44
查看详情 怪兽AI数字人
select.on("change", event => {
    const filterYr = +event.currentTarget.value;
    draw(filterYr);
});
登录后复制

这段代码监听了下拉菜单的change事件,并在事件触发时调用draw函数,并将选定的年份作为参数传递给draw函数。 注意这里使用了 +event.currentTarget.value 将字符串转换为数字。

5. 创建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")
    .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);
登录后复制

这段代码创建了一个SVG容器,并设置了其宽度、高度和内边距。 重要的是,我们将 g 元素(用于容纳文本元素)创建在 draw 函数之外,这样可以避免每次 draw 函数执行时都重复创建 g 元素,从而确保 enter、update 和 exit 选择能够正确工作。

6. 绘制图表

现在,我们可以编写draw函数来绘制图表。

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

function draw(filterYr) {

    // filter data as per dropdown
    const data = src.filter(a => a.Year == filterYr);

    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(year[0]); // Initial draw with the first year
登录后复制

这段代码首先根据选定的年份过滤数据,然后创建X轴和Y轴的比例尺,最后使用D3的join函数来更新图表。 join 函数的 enter 部分处理新添加的数据元素,update 部分处理已存在的数据元素,而 exit 部分(虽然在此示例中被注释掉了)则处理需要移除的数据元素。

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

<body>
    <svg></svg>
    <script>
        // Data generation (same as before)
        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();

        // Dropdown creation
        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);

        // SVG setup
        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;

        svg.append("rect")
            .attr("class", "boundRect")
            .attr("x", `${padding.left}`)
            .attr("y", `${padding.top}`)
            .attr("width", `${boundWidth}`)
            .attr("height", `${boundHeight}`)
            .attr("fill", "white");

        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);

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

        // Draw function
        function draw(filterYr) {
            const data = src.filter(a => a.Year == filterYr);

            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()
                );
        }

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

        // Initial draw
        draw(year[0]);
    </script>
</body>

</html>
登录后复制

8. 注意事项

  • 确保在draw函数之外创建g元素,以避免重复创建。
  • 使用+event.currentTarget.value将下拉菜单的值转换为数字。
  • 根据需要调整比例尺和图表的样式。
  • exit 选择用于移除不再需要的数据元素,可以根据具体需求进行实现。

9. 总结

本文介绍了如何使用D3.js构建一个动态图表,该图表的数据会根据HTML下拉菜单的选择进行更新。通过监听下拉菜单的change事件,并利用D3的join、enter、update模式,我们可以轻松地实现数据的动态更新。希望本文能够帮助你更好地理解D3.js的数据绑定和更新机制,并能够应用到实际的项目中。

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

驱动精灵
驱动精灵

驱动精灵基于驱动之家十余年的专业数据积累,驱动支持度高,已经为数亿用户解决了各种电脑驱动问题、系统故障,是目前有效的驱动软件,有需要的小伙伴快来保存下载体验吧!

下载
来源: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号