d3js 中矩形的大小基于值的总和而不是项目的计数

2023-12-24

我正在开发 d3js 可视化,我想根据大小显示组和子组。除了矩形的大小之外,大部分功能都可以工作。如果您在加载时看到所有四个盒子尺寸都相同,因为它们都有相同的编号。补助金计划。我想根据 grant_award 更改这些矩形的大小。这是我在以下位置发布的代码:

https://gist.github.com/senthlthyagarajan/bfa1b611c0e91b1a304c0b8f32555daf https://gist.github.com/senthilthyagarajan/bfa1b611c0e91b1a304c0b8f32555daf

谢谢


更新:index.js .value()引用总和,以便每个块将根据 value=>sum 分配维度

index.js

var log = console.log;
var margin = {top: 30, right: 0, bottom: 0, left: 0};
var width = 800;
var height = 670 - margin.top - margin.bottom;
var transitioning;

// x axis scale
var x = d3.scale.linear()
.domain([0, width])
.range([0, width]);

// y axis scale
var y = d3.scale.linear()
.domain([0, height])
.range([0, height]);



// treemap layout
var treemap = d3.layout.treemap()
.children(function(d, depth) { return depth ? null : d._children; })
.sort(function(a, b) { return a.value - b.value; })
.ratio(height / width * 0.5 * (1 + Math.sqrt(5)))
.value(d=>d.sum)
.round(false);

// define svg
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.bottom + margin.top)
.style("margin-left", -margin.left + "px")
.style("margin.right", -margin.right + "px")
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`)
.style("shape-rendering", "crispEdges");

// top gray rectangle
var grandparent = svg.append("g")
.attr("class", "grandparent");

// Add grandparent rect
grandparent.append("rect")
.attr("y", -margin.top)
.attr("width", width)
.attr("height", margin.top)
.style("fill", "#d9d9d9");

// Add grandparent text
grandparent.append("text")
.attr("class", "title")
.attr("x", 6)
.attr("y", 6 - margin.top)
.attr("dy", ".75em");        

// custom root initializer
function initialize(root) {
  root.x = root.y = 0;
  root.dx = width;
  root.dy = height;
  root.depth = 0;
};

// Aggregate the values for internal nodes. This is normally done by the
// treemap layout, but not here because of our custom implementation.
// We also take a snapshot of the original children (_children) to avoid
// the children being overwritten when when layout is computed.
// Alteration made for function to be iterative
function accumulateVal(d, attr) {
  return accumulate(d);

  function accumulate(d) {
    return (d._children = d.children)
    // recursion step, note that p and v are defined by reduce
    ? d[attr] = d.children.reduce(function(p, v) {return p + accumulate(v); }, 0)
    : d[attr];
  };
};

// Compute the treemap layout recursively such that each group of siblings
// uses the same size (1×1) rather than the dimensions of the parent cell.
// This optimizes the layout for the current zoom state. Note that a wrapper
// object is created for the parent node for each group of siblings so that
// the parent’s dimensions are not discarded as we recurse. Since each group
// of sibling was laid out in 1×1, we must rescale to fit using absolute
// coordinates. This lets us use a viewport to zoom.
function layout(d) {
  if (d._children) {
    // treemap nodes comes from the treemap set of functions as part of d3
    treemap.nodes({_children: d._children});
    d._children.forEach(function(c) {
      c.x = d.x + c.x * d.dx;
      c.y = d.y + c.y * d.dy;
      c.dx *= d.dx;
      c.dy *= d.dy;
      c.parent = d;
      // recursion
      layout(c);
    });
  }
};

d3.csv("Public_Grants_2010-2012(July-28-2018).csv", treeMapZoomable);

function treeMapZoomable(error, grants) {
  if (error) throw error;

  // Define color scale
  var allValues = grants.map(function(d) { return [d["GRANT_PROGRAM"], d["YEAR"]]; })
  .reduce(function(acc, curVal) { return acc.concat(curVal); }, []);
  var scaleOrdNames = [...new Set(allValues)];
  var colorScale = d3.scale.ordinal().domain(scaleOrdNames)
  .range(['#66c2a5','#fc8d62','#8da0cb','#e78ac3','#a6d854','#ffd92f','#e5c494']);

  // Define aggregrated grant programs
  var aggGrantPrograms = d3.nest().key(function(d) { return d.YEAR; })
  .key(function(d) { return d["GRANT_PROGRAM"]; })
  .entries(grants)
  .map(function(d) {
    var dValues = d.values.map(function(g){
      var gValues = g.values;
      var sum = gValues.map(function(p) { return p["GRANT_AWARD"]; })
      .reduce(function(acc, curVal) { return acc + (+curVal); }, 0);

      return {
        name: g.key,
        value: gValues.length,
        sum: sum
      };
    });

    return {
      name: d.key,
      children: dValues
    };
  });

  // Root for hierarchy
  var rootObject = {name: "Audience Segment", children: aggGrantPrograms};

  initialize(rootObject);
  ["value", "sum"].forEach(function(d) { accumulateVal(rootObject, d); });
  layout(rootObject);
  display(rootObject);

  function display(d) {
    // Grandparent when clicked transitions the children out to parent 
    grandparent
    .datum(d.parent)
    .on("click", transition)
    .select("text.title")
    .text(name(d));

    grandparent
    .datum(d.parent)
    .select("rect");

    var g1 = svg.insert("g", ".grandparent")
    .datum(d)
    .attr("class", "depth");

    var g = g1.selectAll("g")
    .data(d._children)
    .enter().append("g");

    // When parent is clicked transitions to children
    g.filter(function(d) { return d._children; })
    .classed("children", true)
    .on("click", transition);

    g.selectAll(".child")
    .data(function(d) { return d._children || [d]; })
    .enter().append("rect")
    .attr("class", "child")
    .call(rect);

    g.append("rect")
    .attr("class", "parent")
    .call(rect)
    .append("title")
    .text(function(d) { return `Audience Segment: ${d.name}`; });

    // Appending year, grants, and sum texts for each g
    var textClassArr = [
      {class: "year", accsor: function(d) { return d.name; }}, 
      {class: "grants", accsor: function(d) { return `${d.value} segments`; }}, 
      {class: "sum", accsor: function(d) { return `${d.sum.toLocaleString()} sample size`; }}
      ];

    textClassArr.forEach(function(p, i) {
      g.append("text")
      .attr("class", p.class)
      .attr("dy", ".5em")
      .text(p.accsor)
      .call(rectText(i));
    });

    function transition(d) {
      if (transitioning || !d) return;
      transitioning = true;

      var g2 = display(d);
      var t1 = g1.transition().duration(750);
      var t2 = g2.transition().duration(750);

      // Update the domain only after entering new elements.
      x.domain([d.x, d.x + d.dx]);
      y.domain([d.y, d.y + d.dy]);

      // Enable anti-aliasing during the transition.
      svg.style("shape-rendering", null);

      // Draw child nodes on top of parent nodes.
      svg.selectAll(".depth").sort(function(a, b) { return a.depth - b.depth; });

      // Fade-in entering text.
      g2.selectAll("text").style("fill-opacity", 0);

      // Transition to the new view.
      textClassArr.forEach(function(d, i) {
        var textClass = `text.${d.class}`;
        var textPlacmt = rectText(i);

        t1.selectAll(textClass).call(textPlacmt).style("fill-opacity", 0);
        t2.selectAll(textClass).call(textPlacmt).style("fill-opacity", 1);
      });

      t1.selectAll("rect").call(rect);
      t2.selectAll("rect").call(rect);

      // Remove the old node when the transition is finished.
      t1.remove().each("end", function() {
        svg.style("shape-rendering", "crispEdges");
        transitioning = false;
      });                 
    };

    return g;
  };

  function rectText(i) {
    return grantText;

    function grantText(text) {
      return text.attr("x", function(d) { return x(d.x) + 6; })
      .attr("y", function(d) { return y(d.y) + (25 + (i * 18)); })
      .attr("fill", "black");
    };
  };

  function rect(rect) {
    rect.attr("x", function(d) { return x(d.x); })
    .attr("y", function(d) { return y(d.y); })
    .attr("width", function(d) { return x(d.x + d.dx) - x(d.x); })
    .attr("height", function(d) { return y(d.y + d.dy) - y(d.y); })
    .attr("fill", function(d) { return colorScale(d.name);});
  };

  function name(d) {
    return d.parent
    ? `${name(d.parent)}.${d.name} - Total Segments: ${d.value} - 
      Sample Size: ${d.sum.toLocaleString()}`
    : d.name;
  };

};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

d3js 中矩形的大小基于值的总和而不是项目的计数 的相关文章

随机推荐

  • 禁用弹出窗口中的浏览器地址栏

    我有以下带有 Javascript 的 HTML a href Hide Address Bar a 它在 IE 中运行良好 但在 FireFox 3 及更高版本中运行不佳 我想在弹出窗口出现时禁用 位置 栏 问题不是你的语法错误 问题是安
  • R - 如何通过嵌套 tibbles + pwalk(rmarkdown::render) 生成参数化报告

    我正在尝试根据学生数据生成评估报告 我的想法是创建一个 RDS 嵌套 tibble 来传递给rmarkdown render using purrr pwalk 我对 purrr 及其它还比较陌生map函数族 这是有效的代码部分 尝试一下
  • 如何在 haskell 中为这棵树实现 monoid 接口?

    请原谅这些术语 我的思想仍然弯曲 那个树 data Ftree a Empty Leaf a Branch Ftree a Ftree a deriving Show 我有几个问题 If Ftree不可能Empty 它不再是一个Monoid
  • Azure Web api VS 移动服务

    使用时主要区别是什么 Azure Web API 技术上使用 Azure 网站模块 https www windowsazure com en us develop net tutorials rest service using web
  • 从上方查看城市坐标

    作为一个小项目 我一直在考虑创建一个类似 Google 地球的动画 我想在旋转地球以各个城市为中心的同时播放时间线 目前 我可以使用默认视图设置来渲染地球仪 其中城市由点表示 当我尝试使用俯视城市 例如丹佛 的视图向量来调整相机方向时 我最
  • 使用 C# 从 NVarchar(Max) 列流式传输数据

    我想将一些文件的内容放入数据库中以供单独的进程读取 这是一个两步的事情 因为文件将上传到 java 服务器 然后由定期运行的单独的 c 应用程序进行处理 我本来打算使用nvarchar Max 列来表示数据 但我不知道如何以合理的方式从此类
  • MySQL 按小时分组

    我正在尝试按小时使用情况从历史记录表中获取报告 history表是 CREATE TABLE IF NOT EXISTS history history id int 11 unsigned NOT NULL AUTO INCREMENT
  • 错误:由于“_”未定义而无法实例化模块 restangular

    当第一次在工作网站上使用 Restangular 时 我收到以下 JavaScript 错误 由于 未定义 无法实例化模块 restangular 我缺少什么 未定义 在 Restangular 模块中 是什么意思 这是一个简单的疏忽 下划
  • mosquitto 中的地址已在使用错误

    我已经在我的 ubuntu 机器上安装了 mosquitto 服务器和客户端软件包 当我运行命令 mosquitto 来运行 mosquitto 服务器时 我收到错误 错误 地址已在使用中 为什么我会收到此错误 我该如何解决这个问题 我遇到
  • Qt 中的内存管理

    我对 Qt 内存管理有一点疑问 让我们以Listview为例 在listview中我们通过动态分配内存来添加每个项目 那么在这种情况下我们是否需要手动删除所有 新 的项目 E g Qlistview list new Qlistview Q
  • 纱线全局命令不起作用

    我正在使用 Yarn v0 16 1 如果我理解正确的话 根据文档 https yarnpkg com en docs cli global yarn global add
  • sleep 0 在 shell 脚本中做什么?如果在 ansible SSH 配置中使用它在每个命令后附加它会做什么?

    什么是sleep 0在 shell 脚本中做什么 我阅读了 sleep 的手册页 它说 延迟指定的时间 参数 NUMBER 以秒为单位指定这个时间 默认情况下 但我看到 ansible 使用sh c echo ec2 user sleep
  • VSCODE 中的 YAML 文件格式

    我刚刚开始使用 VSCODE 每次在现有 YML 文件中粘贴 YAML 代码时都会遇到麻烦 基本上 编辑器似乎会自动格式化文档 这样做会弄乱文档中的重要空间 这会导致 Azure Devops 中的构建中断 尽管 VS code 可以很好地
  • 发送在我的 NDIS 修改过滤器驱动程序中无法正常工作

    我正在尝试使用 NDIS 来实现数据包修改过滤器 我使用了丢弃数据包并从克隆 NBL 发起发送 接收的方法 msdn 上的文档说这是允许的 https learn microsoft com en us windows hardware d
  • Leaflet/shiny:无法绘制反应多边形

    看完了Leaflet for R 页面上的闪亮集成示例 https rstudio github io leaflet shiny html 我在子集化和显示一些多边形以在我闪亮的应用程序中显示时遇到问题 目前 我正在得到一个带有侧边栏的应
  • phantomjs 没有关闭并留下孤立进程

    在 PhantomJS 1 9 2 ubuntu 12 LTS 和 Ghostdirver 1 04 以及 selenium 2 35 上 测试后我得到了悬空的 phantomjs 进程 有人知道如何解决这个问题的好方法吗 这是一个演示奇怪
  • 使express.js 中单个用户的所有会话失效

    出于安全原因 我们希望能够使用户的所有活动会话无效 例如 如果他们更改密码 或者只是希望能够强制注销其他会话 我们使用 Node js Express express sessions 和 Redis 会话存储 在我们的应用程序中 我们有
  • 除非修改源代码,否则 Three.js 骨骼动画无法工作

    使用 Three js r68 我需要对源代码进行轻微修改才能使我的动画正常工作 未经修改 每种类型的模型中只有一个是动画的 每种类型的模型都有多个生成 这是第 29407 行的修改后的源代码 从 29389 开始发布的代码 THREE A
  • 使用 2.x API 的 Android 应用程序也可以在 1.x 上运行

    我正在开发一个 Android 应用程序 我想在其中使用多点触控 然而 我不想完全忽略那些仍在运行 1 x 操作系统的手机 如何对应用程序进行编程 以便可以使用 2 x 多点触控 API 或与此相关的任何其他更高级别的 API 并且仍然允许
  • d3js 中矩形的大小基于值的总和而不是项目的计数

    我正在开发 d3js 可视化 我想根据大小显示组和子组 除了矩形的大小之外 大部分功能都可以工作 如果您在加载时看到所有四个盒子尺寸都相同 因为它们都有相同的编号 补助金计划 我想根据 grant award 更改这些矩形的大小 这是我在以