在d3堆叠面积图中,鼠标悬停时显示"矩形"内的工具提示值是通过使用d3.js库中的工具提示(Tooltip)功能来实现的。工具提示是一种常见的交互方式,可以在数据可视化图表中显示与鼠标交互相关的信息。
具体实现步骤如下:
<script src="https://d3js.org/d3.v7.min.js"></script>
const width = 500; // 图表宽度
const height = 300; // 图表高度
const margin = { top: 20, right: 20, bottom: 30, left: 50 }; // 图表边距
const svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.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)
.order(d3.stackOrderNone)
.offset(d3.stackOffsetNone);
const series = 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(series, d => d3.max(d, d => d[1]))])
.range([height, 0]);
const area = d3.area()
.x(d => xScale(d.data.category) + xScale.bandwidth() / 2)
.y0(d => yScale(d[0]))
.y1(d => yScale(d[1]));
svg.selectAll("path")
.data(series)
.join("path")
.attr("fill", (d, i) => `rgb(${i * 50}, ${i * 50}, ${i * 50})`)
.attr("d", area);
const tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
svg.selectAll("path")
.on("mouseover", (event, d) => {
const total = d3.sum(d, e => e[1] - e[0]);
const category = d.key;
const value = d3.format(".2f")(total);
tooltip.transition()
.duration(200)
.style("opacity", 0.9);
tooltip.html(`Category: ${category}<br/>Value: ${value}`)
.style("left", (event.pageX) + "px")
.style("top", (event.pageY - 28) + "px");
})
.on("mouseout", () => {
tooltip.transition()
.duration(500)
.style("opacity", 0);
});
通过以上步骤,我们可以在d3堆叠面积图中实现鼠标悬停时显示"矩形"内的工具提示值。当鼠标悬停在某个矩形上时,工具提示会显示该矩形所属的类别(Category)和对应的值(Value)。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)、腾讯云对象存储(COS)、腾讯云数据库MySQL版、腾讯云CDN等。您可以通过访问腾讯云官方网站(https://cloud.tencent.com/)了解更多关于这些产品的详细信息和使用指南。
没有搜到相关的结果
领取专属 10元无门槛券
手把手带您无忧上云