简单的d3.js实现气泡图

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')
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值