createBubbleChart() {
const data = [
{ name: '气泡1', value: 100 },
{ name: '气泡2', value: 30 },
{ name: '气泡3', value: 40 },
// 其他气泡的数据
];
const container = d3.select('#chartContainer'); //容器,#id选择器
// 定义绘图区域的宽度和高度
const width = container.node().clientWidth;
const height = container.node().clientHeight;
// 创建一个层级布局
const pack = d3.pack()
.size([width, height])
.padding(10); // 设置气泡之间的间距
// 转换数据为层级结构
const root = d3.hierarchy({ children: data })
.sum(d => d.value);
// 布局计算
pack(root);
// 创建一个包含气泡和文字的容器元素
const bubbleContainer = container.append('svg')
.attr('width', width)
.attr('height', height);
// 创建气泡元素
const bubbles = bubbleContainer.selectAll('circle')
.data(root.leaves())
.enter()
.append('circle')
.attr('cx', d => 0) //水平位置
.attr('cy', d => d.y) //垂直位置
.attr('r', d => d.r) //半径
.attr('fill', (d, i) => (i === 0) ? 'steelblue' : 'orange') //颜色
.on('mouseover', function() {
d3.select(this).attr('fill', 'red'); // 鼠标悬停时改变颜色为红色
})
.on('mouseout', function() {
d3.select(this).attr('fill', (d, i) => (i === 0) ? 'steelblue' : 'orange'); // 鼠标移出时恢复原来的颜色
})
.transition() // 添加过渡效果(切记一定要在时间监听后面,不然会报错)
.duration(1000) // 过渡持续时间
.attr('cx', (d: any) => d.x);
// 创建文字元素并居中显示
const texts = bubbleContainer.selectAll('text')
.data(root.leaves())
.enter()
.append('text')
.text(d => d.data.name)
.attr('text-anchor', 'middle') // 设置文字居中对齐
.attr('x', d => d.x)
.attr('y', d => d.y)
.attr('dy', '0.35em') // 垂直偏移量,用于居中显示
.style('fill', 'white')
.style('font-size', '12px')
.style('text-anchor', 'middle')
}
简单的d3.js实现气泡图
最新推荐文章于 2024-04-26 16:47:03 发布