
本文档将指导你如何使用D3.js构建一个动态图表,该图表的数据会根据HTML下拉菜单的选择进行更新。我们将重点讲解如何监听下拉菜单的`change`事件,以及如何利用D3的`join`、`enter`、`update`模式来实现数据的动态更新。通过本文,你将学会如何将用户交互与D3.js的数据可视化结合起来,创建更具交互性的Web应用。
首先,确保你已经引入了D3.js库。你可以通过以下方式在HTML文件中引入:
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></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();这段代码生成一个名为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创建了一个下拉菜单,并将年份数据绑定到下拉菜单的选项中。
现在,我们需要监听下拉菜单的change事件,以便在用户选择不同的年份时更新图表。
select.on("change", event => {
const filterYr = +event.currentTarget.value;
draw(filterYr);
});这段代码监听了下拉菜单的change事件,并在事件触发时调用draw函数,并将选定的年份作为参数传递给draw函数。 注意这里使用了 +event.currentTarget.value 将字符串转换为数字。
在绘制图表之前,我们需要创建一个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 选择能够正确工作。
现在,我们可以编写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 部分(虽然在此示例中被注释掉了)则处理需要移除的数据元素。
<!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>本文介绍了如何使用D3.js构建一个动态图表,该图表的数据会根据HTML下拉菜单的选择进行更新。通过监听下拉菜单的change事件,并利用D3的join、enter、update模式,我们可以轻松地实现数据的动态更新。希望本文能够帮助你更好地理解D3.js的数据绑定和更新机制,并能够应用到实际的项目中。
以上就是使用D3.js实现下拉菜单驱动的数据更新的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号