D3.js下拉联动图表更新教程
本文详细介绍了如何利用 D3.js 实现下拉联动更新图表的交互效果。通过监听 HTML 下拉菜单的 `change` 事件,教程将指导你如何动态地过滤数据,并使用 D3.js 强大的 `join`, `enter`, `update`, `exit` 模式,高效地更新 SVG 图表元素,从而实现数据驱动视图的动态变化。本教程从数据准备、HTML下拉菜单创建、事件监听、SVG画布创建,到核心的图表绘制与更新函数 `draw()` 的实现,进行了深入浅出的讲解,并附带完整代码示例,助你轻松掌握 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 下拉菜单的选择进行动态更新的图表。 关键步骤包括:
- 创建下拉菜单: 使用 D3.js 创建 HTML 下拉菜单,并绑定年份数据。
- 监听 change 事件: 监听下拉菜单的 change 事件,获取选中的年份值。
- 数据过滤: 根据选中的年份值过滤数据集。
- 绘制图表: 使用 D3.js 的 join, enter, update, exit 模式更新图表元素。
希望本教程能够帮助你更好地理解 D3.js 的数据绑定和动态更新机制,并将其应用到你的可视化项目中。
好了,本文到此结束,带大家了解了《D3.js下拉联动图表更新教程》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!
JavaScriptreduce方法实用教程
- 上一篇
- JavaScriptreduce方法实用教程
- 下一篇
- Python安装cv2模块方法详解
-
- 文章 · 前端 | 1小时前 |
- Flex布局order和align-self实战技巧
- 274浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- CSS设置元素宽高方法详解
- 359浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- JavaScript宏任务与CPU计算解析
- 342浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- float布局技巧与应用解析
- 385浏览 收藏
-
- 文章 · 前端 | 2小时前 | JavaScript模块化 require CommonJS ES6模块 import/export
- JavaScript模块化发展:CommonJS到ES6全解析
- 192浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- jQueryUI是什么?功能与使用详解
- 360浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- 搭建JavaScript框架脚手架工具全攻略
- 149浏览 收藏
-
- 文章 · 前端 | 2小时前 | JavaScript Bootstrap 响应式设计 CSS框架 Tab切换布局
- CSS实现Tab切换布局教程
- 477浏览 收藏
-
- 文章 · 前端 | 2小时前 |
- 并发控制:限制异步请求数量方法
- 313浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3180次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3391次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3420次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4526次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3800次使用
-
- JavaScript函数定义及示例详解
- 2025-05-11 502浏览
-
- 优化用户界面体验的秘密武器:CSS开发项目经验大揭秘
- 2023-11-03 501浏览
-
- 使用微信小程序实现图片轮播特效
- 2023-11-21 501浏览
-
- 解析sessionStorage的存储能力与限制
- 2024-01-11 501浏览
-
- 探索冒泡活动对于团队合作的推动力
- 2024-01-13 501浏览

