
本文档旨在指导开发者如何使用 D3.js 结合 `join`, `enter`, `update`, `exit` 模式,实现一个通过 HTML 下拉菜单选择数据,并动态更新图表的交互式可视化效果。重点在于监听下拉菜单的 `change` 事件,并将选择的值传递给更新图表的函数,从而实现图表的动态刷新。
首先,需要准备用于生成图表的数据。以下代码生成一个包含年份、名称、排名和值的源数据 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 - https://stackoverflow.com/questions/9960908/permutations-in-javascript/24622772#24622772
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();使用 D3.js 创建一个 HTML 下拉菜单,并使用年份数据填充选项。关键在于为下拉菜单添加 change 事件监听器,以便在用户选择不同年份时触发图表更新。
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)
select.on("change", event => {
const filterYr = +event.currentTarget.value;
draw(filterYr);
});注意:
创建一个 SVG 元素,用于绘制图表。设置 SVG 的 viewBox 属性,使其具有响应式特性。
//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");
//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 坐标。根据实际需求选择合适的比例尺类型(如线性比例尺、时间比例尺等)。
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));使用 D3.js 的 join, enter, update, exit 模式,根据选定的年份数据绘制图表。在 draw() 函数中,首先过滤数据,然后使用 selectAll().data().join() 方法更新图表元素。
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")
)
}
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>D3.js Dropdown Update</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<svg width="960" height="500"></svg>
<script>
////////////////////////////////////////////////////////////
//////////////////////// 00 BUILD DATA//////// /////////////
////////////////////////////////////////////////////////////
//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 - https://stackoverflow.com/questions/9960908/permutations-in-javascript/24622772#24622772
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();
////////////////////////////////////////////////////////////
//////////////////////// 0 BUILD HTML DROPDOWN /////////////
////////////////////////////////////////////////////////////
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);
});
////////////////////////////////////////////////////////////
//////////////////////// 1 DATA WRANGLING //////////////////
////////////////////////////////////////////////////////////
const xAccessor = (d) => d.Year;
const yAccessor = (d) => d.Value;
////////////////////////////////////////////////////////////
//////////////////////// 2 CREATE SVG //////////////////////
////////////////////////////////////////////////////////////
//namespace
//define dimension
const width = 960;
const height = 500;
const svg = d3.select("svg");
////////////////////////////////////////////////////////////
//////////////////////// 3 CREATE BOUND ////////////////////
////////////////////////////////////////////////////////////
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 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);
////////////////////////////////////////////////////////////
//////////////////////// 4 CREATE SCALE ////////////////////
////////////////////////////////////////////////////////////
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")
)
}
draw(filterYr);
</script>
</body>
</html>通过以上步骤,可以实现一个基于 D3.js 的、能够根据下拉菜单选择动态更新的图表。 核心在于监听下拉菜单的 change 事件,并利用 join, enter, update, exit 模式高效地更新图表元素。 在实际应用中,可以根据具体需求调整数据处理、比例尺和图表类型的实现方式。
以上就是使用 D3.js 实现下拉菜单联动更新图表的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号