Typescript中的工具提示(Tooltip)是一种在用户将鼠标悬停在特定元素上时显示的信息框。它可以提供有关该元素的额外信息,例如说明、注释、数据值等。在d3堆叠条形图中实现鼠标悬停的方法如下:
<div id="chart"></div>
import * as d3 from 'd3';
const svgWidth = 500;
const svgHeight = 300;
const margin = { top: 20, right: 20, bottom: 30, left: 50 };
const width = svgWidth - margin.left - margin.right;
const height = svgHeight - margin.top - margin.bottom;
const svg = d3.select("#chart")
.append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const data = [
{ category: "A", value1: 10, value2: 20, value3: 30 },
{ category: "B", value1: 15, value2: 25, value3: 35 },
{ category: "C", value1: 20, value2: 30, value3: 40 },
];
const keys = ["value1", "value2", "value3"];
const stack = d3.stack().keys(keys);
const stackedData = stack(data);
const xScale = d3.scaleBand()
.domain(data.map(d => d.category))
.range([0, width])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(stackedData, d => d3.max(d, d => d[1]))])
.range([height, 0]);
const bars = svg.selectAll("g")
.data(stackedData)
.enter()
.append("g")
.attr("fill", (d, i) => `rgb(${i * 50}, ${i * 50}, ${i * 50})`);
bars.selectAll("rect")
.data(d => d)
.enter()
.append("rect")
.attr("x", d => xScale(d.data.category))
.attr("y", d => yScale(d[1]))
.attr("height", d => yScale(d[0]) - yScale(d[1]))
.attr("width", xScale.bandwidth())
.attr("title", d => d[1] - d[0]); // 设置工具提示的内容
const tooltip = d3.select("#chart")
.append("div")
.style("position", "absolute")
.style("visibility", "hidden");
bars.selectAll("rect")
.on("mouseover", function (event, d) {
const tooltipContent = `Value: ${d[1] - d[0]}`;
tooltip.html(tooltipContent)
.style("visibility", "visible")
.style("top", `${event.pageY}px`)
.style("left", `${event.pageX}px`);
})
.on("mouseout", function () {
tooltip.style("visibility", "hidden");
});
通过上述步骤,你可以在d3堆叠条形图中实现鼠标悬停效果,并显示工具提示。当鼠标悬停在条形图上时,工具提示会显示该条形图的值。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云对象存储(COS)。
希望以上信息对你有帮助!如果还有其他问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云