viewof chart_river = {
const svg = d3
.create("svg")
.attr("viewBox", [0, 0, width, height])
.on("mouseover", reset);
let currentWord = '';
let value = "ALL";
svg
.append("g")
.selectAll("path")
.data(series)
.join("path")
.on("mouseover", over)
.on("mouseout", out)
.on("mousemove", move)
.style("fill", (d) => { return colorScale(d.key); })
.attr("opacity", .7)
.attr("stroke", 'black')
.attr("stroke-width", .2)
.attr("d", area)
.on("click", function(event,d) {
d3.select(this)
.transition()
.attr("opacity", .9)
const node = svg.node();
node.value = value = truncatedseries[d].key;
node.dispatchEvent(new CustomEvent("input"));
});
//画x轴
svg.append("g").call(xAxis);
//画长线
const bigLine = svg
.append("line")
.attr("stroke", "black")
.attr("opacity", .8)
.attr("stroke-dasharray", 3, 4)
.attr("pointer-events", "none");
//画短线
const line = svg
.append("line")
.attr("stroke", "black")
.attr("stroke-width", 2)
.attr("pointer-events", "none");
const textArea = svg.append("g").attr("pointer-events", "none");
const stateLabel = textArea
.append("text")
.attr("font-size", 16)
.attr("text-anchor", "middle");
const caseLabel = textArea
.append("text")
.attr("font-size", 16)
.attr("text-anchor", "middle");
function over(d) {
d3.select(this).attr("opacity", 1);
currentWord = d.key;
d3.event.stopPropagation(); //停止传播???
}
function out(d) {
d3.select(this).attr("opacity", .7);
}
function move(d) {
const dateStamp =
x.invert(d3.event.offsetX).getTime() >
x.invert(d3.event.offsetX).setHours(12, 0, 0, 0)
? x.invert(d3.event.offsetX).setHours(24, 0, 0, 0)
: x.invert(d3.event.offsetX).setHours(0, 0, 0, 0);
const index = d.findIndex(t => t.data.Date.getTime() == dateStamp);
const selectedData = d[index];
// const node = svg.node();
// node.value = value = "ALL";
// node.dispatchEvent(new CustomEvent("input"));
const min = d3.min(series, d => d[index][0]);
const max = d3.max(series, d => d[index][1]);
line
.attr("x1", x(dateStamp))
.attr("x2", x(dateStamp))
.attr("y1", y(selectedData[0]))
.attr("y2", y(selectedData[1]));
bigLine
.attr("x1", x(dateStamp))
.attr("x2", x(dateStamp))
.attr("y1", y(min))
.attr("y2", y(max));
stateLabel
.attr("x", d3.max([d3.min([x(dateStamp), width - 120]), 120]))
.attr("y", d3.max([y(max) - 40, 20]))
.text(currentWord + ' ' + new Date(dateStamp).toLocaleDateString());
const stateMetric = selectedData.data[currentWord];
const nationalMetric = d3.sum(keys, k => selectedData.data[k]);
const percentage = Math.round((stateMetric / nationalMetric) * 100);
caseLabel
.attr("x", d3.max([d3.min([x(dateStamp), width - 120]), 120]))
.attr("y", d3.max([y(max) - 20, 40]))
.text(
` 数量:${Math.round(
stateMetric
)} 占比:${percentage}%`
);
d3.event.stopPropagation();
}
function reset() {
line
.attr("x1", 0)
.attr("x2", 0)
.attr("y1", 0)
.attr("y2", 0);
bigLine
.attr("x1", 0)
.attr("x2", 0)
.attr("y1", 0)
.attr("y2", 0);
stateLabel.text("");
caseLabel.text("");
}
return Object.assign(svg.node(), {value});
}