
本文档旨在指导开发者如何使用 D3.js 结合 HTML 下拉菜单(`
首先,我们需要准备用于生成图表的数据。以下代码生成一个包含年份、名称、排名和数值的示例数据集。
// 期望的排列长度
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();这段代码生成一个名为 src 的数组,其中包含了后续图表需要用到的数据。
接下来,我们需要在 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 数组填充下拉菜单的选项。每个选项的文本和值都设置为对应的年份。
关键在于监听下拉菜单的 change 事件,并在事件触发时更新图表。
select.on("change", event => {
const filterYr = +event.currentTarget.value;
draw(filterYr);
});这段代码监听 select 元素的 change 事件。当用户选择不同的年份时,event.currentTarget.value 获取选中的年份值,并将其传递给 draw() 函数。注意,这里使用了 + 运算符将字符串转换为数字。
在 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 元素,导致图表元素重复添加。
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 选择用于移除不再需要的元素。
注意:
最后,需要在页面加载时调用一次 draw() 函数,以便显示初始数据。
draw(filterYr);
这段代码在页面加载时调用 draw() 函数,并传入初始的 filterYr 值。
<!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>Document</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<svg></svg>
<script>
// 数据准备(与前面相同)
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();
// 构建 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);
</script>
</body>
</html>通过以上步骤,我们成功地使用 D3.js 和 HTML 下拉菜单实现了动态数据更新。 关键点包括:
掌握这些技术,可以为用户提供更加交互性强、动态的可视化体验。
以上就是使用 D3.js 实现基于下拉菜单的动态数据更新的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号