【问题标题】:Using D3.js to create a simple treemap使用 D3.js 创建一个简单的树形图
【发布时间】:2021-04-19 02:07:39
【问题描述】:

我有一些 csv 数据,我计算每个项目的出现次数以获取表示每个不同项目的计数的整数数组。我想使用 D3.js v5 创建一个树形图,其中每个矩形的大小与这些数字成正比。我见过的树形图上的所有资源都使用层次结构和树来创建它。是否可以仅使用代表区域的数字创建一个非常基本的树形图?

像这样: Treemap example

【问题讨论】:

  • 请张贴想要的结果的图片,它可以帮助...
  • 使用示例图片编辑帖子

标签: javascript html d3.js


【解决方案1】:

这是一个示例:

const data = [300, 200, 150, 100, 50].sort((a,b) => b - a);
const sum = data.reduce((s, i) => s + i, 0);

const svg = d3.select('svg');
const width = parseInt(svg.attr('width'));
const height = parseInt(svg.attr('height'));
const unit = width * height / sum;
const bounds = {top: 0, left: 0, right: width, bottom: height}; 

let weightLeft = sum;
let x, y, w, h;

data.forEach(d => {
  const hSpace = bounds.right - bounds.left;
  const vSpace = bounds.bottom - bounds.top;
  const area = d / unit;
  x = bounds.left;
  y = bounds.top;
  if (hSpace > vSpace) {
    w = (d / weightLeft) * hSpace;
    h = vSpace;
    bounds.left = x + w;
  }
  else {
    w = hSpace;
    h = (d / weightLeft) * vSpace;
    bounds.top = y + h;
  }
  weightLeft -= d;
  svg.append('rect')
    .attr('x', x)
    .attr('y', y)
    .attr('width', w)
    .attr('height', h)
    .style('fill', 'blue')
    .style('stroke', 'white')
    .style('stroke-width', 3)
  svg.append('text')
    .text(d)
    .attr('x', x + w/2)
    .attr('y', y + h/2)
    .attr('text-anchor', 'middle')
    .attr('alignment-baseline', 'middle')
    .style('fill', 'white')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="250" height="200" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2021-07-22
    • 2016-06-03
    • 1970-01-01
    相关资源
    最近更新 更多