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

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

本文档旨在指导开发者如何使用 D3.js 结合 HTML 下拉菜单(“ 元素)实现动态数据更新。通过监听下拉菜单的 `change` 事件,并利用 D3.js 的 `join, enter, update, exit` 模式,可以根据用户的选择实时更新可视化图表,提供交互性更强的用户体验。本文将提供详细的代码示例和步骤说明,帮助读者理解和掌握这一技术。

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 + 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 元素,导致图表元素重复添加。

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. 完整代码示例

                Document                    // 数据准备(与前面相同)        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 + 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);    

8. 总结

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

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1584462.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月23日 00:54:14
下一篇 2025年12月23日 00:54:29

相关推荐

发表回复

登录后才能评论
关注微信