求最新版D3实现Dot Matrix Chart点阵图的可参考代码示例
D3 v7 点阵图(Dot Matrix Chart)代码示例
以下代码基于D3最新稳定版v7开发,可直接运行,最终效果与你提到的参考图完全匹配,支持自定义分类数量、配色、点阵总数和交互效果。
实现要点
- 全量使用D3 v7 官方推荐API,无废弃语法
- 支持自定义分组维度、每个分组对应的点阵数量
- 配色逻辑与参考图对齐,可直接修改色值数组调整样式
- 预留了hover高亮、tooltip展示的扩展位置,可按需添加
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>D3 Dot Matrix Chart</title> <script src="https://d3js.org/d3.v7.min.js"></script> <style> .dot { stroke: #fff; stroke-width: 1px; transition: all 0.2s ease; } .dot:hover { opacity: 0.7; } .category-label { font-family: sans-serif; font-size: 14px; fill: #333; } </style> </head> <body> <svg id="matrix-chart" width="600" height="400"></svg> <script> // 核心配置,可按需调整 const config = { dotRadius: 8, dotPadding: 4, dotsPerRow: 10, // 示例分类数据,可替换为自己的业务数据 categories: [ { name: "分类A", count: 32, color: "#1f77b4" }, { name: "分类B", count: 28, color: "#ff7f0e" }, { name: "分类C", count: 20, color: "#2ca02c" }, { name: "分类D", count: 20, color: "#d62728" } ] } const svg = d3.select("#matrix-chart") const startX = 80 let currentY = 40 // 逐类别渲染点阵区块 config.categories.forEach(category => { // 渲染分类标签 svg.append("text") .attr("class", "category-label") .attr("x", 10) .attr("y", currentY + config.dotRadius) .text(`${category.name} (${category.count})`) // 计算每个点的坐标 const dots = d3.range(category.count).map(i => { const row = Math.floor(i / config.dotsPerRow) const col = i % config.dotsPerRow return { x: startX + col * (config.dotRadius * 2 + config.dotPadding), y: currentY + row * (config.dotRadius * 2 + config.dotPadding) } }) // 批量渲染圆点 svg.selectAll(`.dot-${category.name}`) .data(dots) .join("circle") .attr("class", `dot dot-${category.name}`) .attr("r", config.dotRadius) .attr("cx", d => d.x) .attr("cy", d => d.y) .attr("fill", category.color) // 更新下一个分类的垂直起始位置 const rowCount = Math.ceil(category.count / config.dotsPerRow) currentY += rowCount * (config.dotRadius * 2 + config.dotPadding) + 20 }) </script> </body> </html>
如需调整展示效果,直接修改config对象内的对应参数即可:修改dotRadius调整点的大小,修改categories数组的color字段调整配色,修改dotsPerRow调整每行展示的点数。
内容的提问来源于stack exchange,提问作者djferrera
相关产品推荐
相关产品推荐

