D3推荐教程:https://b23.tv/Upvxdu

代码源文件:http://sunie.top:9009/index.php?dir=/Server/html/visualization

一、D3 interaction

1. 原始文件

2. 课堂任务

  • 任务1:鼠标进入柱子时,将柱状图文字的绝对值改为相对值
  • 任务2:鼠标进入柱子时,绘制等高线(提示,等高线的始末位置为(0,y)->(width,y))
  • 任务3:退出柱子时,去除等高线

3. 最终效果

4. 增量代码

// --------------任务1:鼠标进入柱子时,将柱状图文字的绝对值改为相对值--------------
const divergence = (a.value - actual.value).toFixed(1)

let text = ''
if (divergence > 0) text += '+'
text += `${divergence}%`
return idx !== i ? text : '';

//  --------------任务2:鼠标进入柱子时,绘制等高线(提示,等高线的始末位置为(0,y)->(width,y))------------
line = chart.append('line')
.attr('id', 'limit')
.attr('x1', 0)
.attr('y1', y)
.attr('x2', width)
.attr('y2', y)
.style('stroke', 'white')
.style('stroke-width', 3)
.style('stroke-dasharray', 6)

//  --------------任务3:退出柱子时,去除等高线--------------
chart.selectAll('#limit').remove()

二、D3 anination

1. 原始文件

2. 课堂任务

任务:鼠标进入柱子时,将柱状图顶部文字的绝对值改为相对值
提示:类别为:valueLabel,相对值为:d.value-actual.value,有以下三种方法,选择一种即可

  1. 可以使用上节课的内容:设置现有的文字透明,再加入新的文字
  2. 也可以使用本次讲的update方法切换
  3. 有能力的同学可以进一步使用update+tween方法,切换时有动画过渡

3. 最终效果

4. 增量代码

				// 1.可以使用上节课的内容:设置现有的文字透明,再加入新的文字
				svg.selectAll(".valueLabel").attr("opacity", 0);
				svg.selectAll("text.divergence")
					.data(yearSlice, (d) => d.name)
					.enter()
					.append("text")
					.attr("class", "divergence")
					.attr("x", (d) => x(d.value) + 5)
					.attr("y", (d) => y(d.rank) + 5 + (y(1) - y(0)) / 2 + 1)
					.text((d, idx) =>
						d3.format(",.0f")(d.value - actual.value)
					);

				// 2.也可以使用本次讲的update方法切换(推荐)
				svg.selectAll(".valueLabel")
					.data(yearSlice, (d) => d.name)
					.transition()
					.attr("x", (d) => x(d.value) + 5)
					.attr("y", (d) => y(d.rank) + 5 + (y(1) - y(0)) / 2 + 1)
					.text((d) => d3.format(",.0f")(d.value - actual.value));

				// 3.有能力的同学可以进一步使用update+tween方法,切换时有动画过渡
				svg.selectAll(".valueLabel")
					.data(yearSlice, (d) => d.name)
					.transition()
					.attr("x", (d) => x(d.value) + 5)
					.attr("y", (d) => y(d.rank) + 5 + (y(1) - y(0)) / 2 + 1)
					.duration(300)
					.ease(d3.easeLinear)
					.tween("text", function (d) {
						let i = d3.interpolateRound(
							d.value,
							d.value - actual.value
						);
						return function (t) {
							this.textContent = d3.format(",")(i(t));
						};
					});

三、D3 linked view

1. 原始文件

2. 课堂任务

任务:添加link chart动作
提示:基本上与area1链接area2一致:

  1. 选中对应的位置,设置mouseover, mouseout函数
  2. 将选中的元素置位active,并添加悬浮标签
  3. 将折线图中active的元素类置为 pathLight

3. 最终效果

4. 增量代码

		d3.selectAll("rect")
		.on("mouseover", function (d) {
			activeDistrict = d.district;

			appendHoverLabel();

			d3.selectAll("path").classed("pathLight", (d) => {
				// console.log(d);
				return d.district == activeDistrict;
			});
		})

		.on("mouseout", function () {
			d3.selectAll("path").attr("class", "pathBase");

			d3.select("#hoverLabel").remove();
		});