D3.js:如何在版本 4 中向直方图添加分布线

2024-02-12

Note: 这个问题 https://stackoverflow.com/questions/41248649/d3-js-how-to-add-distribution-curves-to-histograms-in-version-4是关于curves.

This is my current status: enter image description here

我不太明白如何绘制两个分布line对于直方图,您会看到我的尝试在代码中被注释掉。我的主要问题是如何给出 x 和 y 参数,因为每个观测值仅附加一个值。

这是我的代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <style>
    .bar1 rect {
      fill: rgba(0,0,255,0.6);
    }

    .bar1:hover rect{
      fill: rgba(0,0,255,0.9);
    }

    .bar1 text {
      fill: #fff;
      font: 10px sans-serif;
    }

    .bar2 rect {
      fill: rgba(255,0,0,0.6);
    }

    .bar2:hover rect{
      fill: rgba(255,0,0,0.9);
    }

    .bar2 text {
      fill: #fff;
      font: 10px sans-serif;
    }

    </style>
    <script src="https://d3js.org/d3.v4.min.js"></script>

    <script>

    function draw(data) {

      var allCongruentData = data.map(function(e){ return e.Congruent;});
      var allIncongruentData = data.map(function(e){ return e.Incongruent;});

      var formatCount = d3.format(",.0f");

      var svg = d3.select("svg"),
          margin = {top: 10, right: 30, bottom: 30, left: 30},
          width = +svg.attr("width") - margin.left - margin.right,
          height = +svg.attr("height") - margin.top - margin.bottom,
          g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      var x = d3.scaleLinear()
          .rangeRound([0, width])
          .domain([8, 36]);

      var bins1 = d3.histogram()
          .domain(x.domain())
          .thresholds(x.ticks(40))
          (allCongruentData);

      // var line = d3.line()
      //       .x(function(d) { return ???; })
      //       .y(function(d) { return y(d.Congruent); })
      //       .curve(d3.curveCatmullRom.alpha(0.5));

      var bins2 = d3.histogram()
          .domain(x.domain())
          .thresholds(x.ticks(40))
          (allIncongruentData);

      var y = d3.scaleLinear()
          .domain([0, d3.max(bins1, function(d) { return d.length; })])
          .range([height, 0]);

      var bar1 = g.selectAll(".bar1")
        .data(bins1)
        .enter().append("g")
          .attr("class", "bar1")
          .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });

      bar1.append("rect")
          .attr("x", 0.5)
          .attr("width", x(bins1[0].x1) - x(bins1[0].x0) - 1)
          .attr("height", function(d) { return height - y(d.length); });


      var bar2 = g.selectAll(".bar2")
        .data(bins2)
        .enter().append("g")
          .attr("class", "bar2")
          .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });

      bar2.append("rect")
          .attr("x", 0.5)
          .attr("width", x(bins2[0].x1) - x(bins2[0].x0) - 1)
          .attr("height", function(d) { return height - y(d.length); });

      bar1.append("text")
          .attr("dy", ".75em") // why?
          .attr("y", 6)
          .attr("x", (x(bins1[0].x1) - x(bins1[0].x0)) / 2)
          .attr("text-anchor", "middle")
          .text(function(d) { return formatCount(d.length); });

      bar2.append("text")
          .attr("dy", ".75em") // why?
          .attr("y", 6)
          .attr("x", (x(bins2[0].x1) - x(bins2[0].x0)) / 2)
          .attr("text-anchor", "middle")
          .text(function(d) { return formatCount(d.length); });

      g.append("g")
          .attr("class", "axis axis--x")
          .attr("transform", "translate(0," + height + ")")
          .call(d3.axisBottom(x));

      var legend = svg.append("g")
              .attr("class", "legend")
              .attr("transform", "translate(" + (width - 245) + "," + 40 + ")")
              .selectAll("g")
              .data(["Congruent", "Incongruent"])
              .enter().append("g");

          legend.append("text")
              .attr("y", function(d, i) {
                  return i * 30 + 5;
              })
              .attr("x", 200)
              .text(function(d) {
                  return d;
              });

          legend.append("rect")
              .attr("y", function(d, i) {
                  return i * 30 - 8;
              })
              .attr("x", 167)
              .attr("width", 20)
              .attr("height", 20)
              .attr("fill", function(d) {
                  if (d == "Congruent") {
                      return 'rgba(0,0,255,0.6';
                  } else {
                      return 'rgba(255,0,0,0.6';
                  }
              });

      // g.append("path")
      //     .datum(data)
      //     .attr("d", line);

    }
    </script>
  </head>
  <body>
    <h1>Stroop Test</h1>
    <svg width="960" height="500"></svg>
    <script type="text/javascript">
      d3.csv("stroopdata.csv", function(d) {
          d.Congruent = +d.Congruent;
          d.Incongruent = +d.Incongruent;
          return d;
        }, draw);
    </script>
  </body>
</html>

数据如下:

Congruent,Incongruent
12.079,19.278
16.791,18.741
9.564,21.214

任何帮助表示赞赏。


你想多了。很简单:

  var line = d3.line()
      .x(function(d) { return x((d.x0 + d.x1)/2); })
      .y(function(d) { return y(d.length); })
      .curve(d3.curveCatmullRom.alpha(0.5));

  g.append("path")
   .attr("d", line(bins1))
   .attr("class", "bins1");

  g.append("path")
   .attr("d", line(bins2))
   .attr("class", "bins2");

运行代码:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <style>
    .bar1 rect {
      fill: rgba(0, 0, 255, 0.6);
    }
    
    path.bins1 {
      stroke: rgba(0, 0, 255, 0.6);
      stroke-width: 4px;
      fill: none;
    }
    
    .bar1:hover rect {
      fill: rgba(0, 0, 255, 0.9);
    }
    
    .bar1 text {
      fill: #fff;
      font: 10px sans-serif;
    }
    
    .bar2 rect {
      fill: rgba(255, 0, 0, 0.6);
    }
    
    path.bins2 {
      stroke: rgba(255, 0, 0, 0.6);
      stroke-width: 4px;
      fill: none;
    }
    
    .bar2:hover rect {
      fill: rgba(255, 0, 0, 0.9);
    }
    
    .bar2 text {
      fill: #fff;
      font: 10px sans-serif;
    }
  </style>
  <script src="https://d3js.org/d3.v4.min.js"></script>

  <script>
    function draw(data) {

      var allCongruentData = data.map(function(e) {
        return e.Congruent;
      });
      var allIncongruentData = data.map(function(e) {
        return e.Incongruent;
      });

      var formatCount = d3.format(",.0f");

      var svg = d3.select("svg"),
        margin = {
          top: 10,
          right: 30,
          bottom: 30,
          left: 30
        },
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      var x = d3.scaleLinear()
        .rangeRound([0, width])
        .domain([8, 36]);

      var bins1 = d3.histogram()
        .domain(x.domain())
        .thresholds(x.ticks(40))
        (allCongruentData);

      var line = d3.line()
          .x(function(d) { return x((d.x0 + d.x1)/2); })
          .y(function(d) { return y(d.length); })
          .curve(d3.curveCatmullRom.alpha(0.5));

      var bins2 = d3.histogram()
        .domain(x.domain())
        .thresholds(x.ticks(40))
        (allIncongruentData);

      var y = d3.scaleLinear()
        .domain([0, d3.max(bins1, function(d) {
          return d.length;
        })])
        .range([height, 0]);

      var bar1 = g.selectAll(".bar1")
        .data(bins1)
        .enter().append("g")
        .attr("class", "bar1")
        .attr("transform", function(d) {
          return "translate(" + x(d.x0) + "," + y(d.length) + ")";
        });
        
      g.append("path")
       .attr("d", line(bins1))
       .attr("class", "bins1");

      bar1.append("rect")
        .attr("x", 0.5)
        .attr("width", x(bins1[0].x1) - x(bins1[0].x0) - 1)
        .attr("height", function(d) {
          return height - y(d.length);
        });


      var bar2 = g.selectAll(".bar2")
        .data(bins2)
        .enter().append("g")
        .attr("class", "bar2")
        .attr("transform", function(d) {
          return "translate(" + x(d.x0) + "," + y(d.length) + ")";
        });
        
      g.append("path")
       .attr("d", line(bins2))
       .attr("class", "bins2");

      bar2.append("rect")
        .attr("x", 0.5)
        .attr("width", x(bins2[0].x1) - x(bins2[0].x0) - 1)
        .attr("height", function(d) {
          return height - y(d.length);
        });

      bar1.append("text")
        .attr("dy", ".75em") // why?
        .attr("y", 6)
        .attr("x", (x(bins1[0].x1) - x(bins1[0].x0)) / 2)
        .attr("text-anchor", "middle")
        .text(function(d) {
          return formatCount(d.length);
        });

      bar2.append("text")
        .attr("dy", ".75em") // why?
        .attr("y", 6)
        .attr("x", (x(bins2[0].x1) - x(bins2[0].x0)) / 2)
        .attr("text-anchor", "middle")
        .text(function(d) {
          return formatCount(d.length);
        });

      g.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

      var legend = svg.append("g")
        .attr("class", "legend")
        .attr("transform", "translate(" + (width - 245) + "," + 40 + ")")
        .selectAll("g")
        .data(["Congruent", "Incongruent"])
        .enter().append("g");

      legend.append("text")
        .attr("y", function(d, i) {
          return i * 30 + 5;
        })
        .attr("x", 200)
        .text(function(d) {
          return d;
        });

      legend.append("rect")
        .attr("y", function(d, i) {
          return i * 30 - 8;
        })
        .attr("x", 167)
        .attr("width", 20)
        .attr("height", 20)
        .attr("fill", function(d) {
          if (d == "Congruent") {
            return 'rgba(0,0,255,0.6';
          } else {
            return 'rgba(255,0,0,0.6';
          }
        });

      // g.append("path")
      //     .datum(data)
      //     .attr("d", line);

    }
  </script>
</head>

<body>
  <h1>Stroop Test</h1>
  <svg width="960" height="500"></svg>
  <script type="text/javascript">
    
    var data = [];
    for (var i = 0; i < 50; i++){
      data.push({
        Congruent: (Math.random() * (36 - 8)) + 8,
        Incongruent: (Math.random() * (36 - 8)) + 8
      })
    }
    draw(data);
    
    /*
    d3.csv("stroopdata.csv", function(d) {
      d.Congruent = +d.Congruent;
      d.Incongruent = +d.Incongruent;
      return d;
    }, draw);
    */  
  
  </script>
</body>

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

D3.js:如何在版本 4 中向直方图添加分布线 的相关文章

  • 为什么 window 与 Internet Explorer 中的 window.self 不同?

    关于我如何遇到这个问题有一个复杂的背景故事 但为什么self属性不完全等于窗口本身 在 Safari 和 Firefox 及其朋友中 结果如我所料 gt window window self true gt window window se
  • Number.IsNaN() 比 isNaN() 更糟糕吗

    Soooooo isNaNJavaScript 显然被破坏了 比如 isNaN isNaN isNaN true isNaN false isNaN 0 返回 false 当它们看起来都是 不是数字 在 ECMAScript 6 中 草案包
  • 转义 h 轮廓

    因此 我一直在尝试找出在被较低级别的标题吸引后添加内容的最佳方法是什么 section h1 Title of Section h1 h2 Related 1 h2 h2 Related 2 h2 p I NEED THIS TO BE P
  • 本地推送通知到在应用程序内运行 JS 代码的 Win8 Live Tile

    我正在尝试将更新发送到我的应用程序的磁贴 当应用程序运行时 这可以正常工作 例如 当用户单击按钮时 我可以轻松地将磁贴更新通知发送到磁贴 我无法解决的是当应用程序无法运行时如何更新磁贴 我找到的唯一选择是使用以下命令从远程 Web 服务器拉
  • 两列表:一列尽可能小,另一列占据其余部分

    我在 div 中有一个 to columns 表 div table tbody tr td class action a a td td class content p Bigger text variable size p td tr
  • 如何通过单击链接来更改 div 的内容?

    这是我的网页的 修改后的 jsfiddle 它还有很多 而且定位是正确的 与此相反 http jsfiddle net ry0tec3p 1 http jsfiddle net ry0tec3p 1 a href class btn1 st
  • 如何使用角度材料在具有可扩展行的表格中创建嵌套垫表

    我有以下数据 id c9d5ab1a subdomain wing domain aircraft part id c9d5ab1a info mimetype application json info dependent parent
  • mongodb 聚合 - 累积字段的不同组值

    如果我有Player表格文件 name String score Int 我有Group文档 其中组代表玩家列表 groupName String players ObjectID 玩家可以属于多个组 我想做一个聚合Player文档 按以下
  • 使用 JavaScript 移动页面上的按钮

    我的按钮可以移动 但奇怪的是 我无法弄清楚偏移是否有问题 我希望我的按钮随着鼠标光标移动 但现在它的移动方式不是我想要的 有时它会消失 另外 创建的新按钮是重叠的 我不知道如何解决这个问题并拥有更好的外观 var coorA var coo
  • 如何停止TinyMCE删除span标签?

    在我的工作中 前一位程序员决定使用公司网站上精彩的TinyMCE 我遇到的数千个问题之一是 如果原文有的话span标签 当我按下退格键删除一行 p仅标签 全部span标签已从文本中删除 这个错误比另一个错误更具体 我可以删除anything
  • LeafleteachLayer函数不会迭代所有Layer

    使用 GeoJSON 数据数组创建一些标记 getJSON GetLocationsServlet function data L geoJSON data onEachFeature onEachFeature addTo mymap G
  • Vaadin 12 将对象传递给 JavaScript 函数:无法对类进行编码

    Vaadin 12 Kotlin 项目 In my myPage html我有JavaScript myObject redirectToCheckout sessionId 1111 2222 所以我需要调用javaScript函数red
  • 使用javascript动态更新css内容

    需要将 css 更新为动态值 我不确定最好的方法是什么 div style zoom 1 div 缩放级别将根据窗口大小调整触发 应用程序将相应缩放 我将此应用程序加载到 cordova 中并让它在 iPAD 中运行 然后我意识到需要使用
  • 主页(网格)上的缩略图现在显得模糊。如何纠正?

    我不知道这看起来是否愚蠢 但从早上开始我就无法纠正这个突然出现在我的博客网站上的错误www candidopinions in http www candidopinions in 我有一个网格视图模板 其中博客文章中的特色图像作为调整大小
  • 从 PHP 数组生成 HTML 表

    我不明白这一点 我需要解决看似简单的问题 但这超出了我的逻辑 我需要编写一个函数 table columns input cols 它将输出一个表 示例 input array apple orange monkey potato chee
  • 使用 Enzyme 测试 `React.createRef` api

    我想测试下面的类 它使用React createRef api 不过 快速搜索并没有发现任何这样做的例子 有人成功过吗 我该如何嘲笑裁判 理想情况下我想使用shallow class Main extends React Component
  • 滚动顶部不符合预期

    Note 由于上次忘记奖励而重新开放赏金 A Woff 大师已经给出答案 我想在用户展开某一行时到达该行 这样当最后一个可见行展开时 用户不必向下滚动即可查看内容 I used example tbody on click td green
  • 没有输入的 jQuery 日期选择器

    我有一个相当复杂的网络应用程序 我想向其中添加一些日期选择 UI 我遇到的问题是我无法从文档中弄清楚如何真正控制日期选择器的出现方式和时间 不涉及任何表单元素 不 我不会添加秘密表单字段 因此简单的开箱即用方法根本行不通 我希望有人可以提供
  • 使用velocity.js制作可拖动元素的动画

    我正在使用velocity js 为用户拖动的可拖动 SVG 元素设置动画 然而 velocity js 将先前的 mousemove 坐标排队并通过所有后续的 mousemove 坐标进行动画处理 我想要的是velocity js 不要对
  • 禁用允许文本选择的

    残疾人可以吗

随机推荐

  • 使用 kingfisher lib 插入授权标头字段

    我正在使用 Kingfisher 显示来自 url 的图像 但我的端点需要授权标头 如何在 iOS 中将此类 url 与 Kingfisher 或 SDWebImage 一起使用 使用 Kingfisher 您需要创建一个请求修饰符 类型为
  • 使用 java 的 Dynamodb 使用哪个 jar

    我正在尝试使用 Java 8 为 DynamoDB 编写 DAO 似乎有多种方法 类主要定义在以下两个包下 com amazonaws services dynamodbv2 software amazon awssdk services
  • Android 5.0+ AudioManager setMode 不起作用

    我正在开发 AudioManager 它是一个 Android SystemService 在 Android 系统 5 0 中 我遇到了 AudioManager 的 setMode 方法不起作用的问题 我通过测试 Android M L
  • unicode“感知”std::getline

    好吧 我正在测试如何编写一个 C 应用程序 该应用程序实际上可以读取 和更改 文本文件 同时尊重文本使用的编码 我希望 对于其他 API 将所有读取的文本显式转换为 UTF 8 以供内部使用 与文件中的实际编码无关 我在 Windows 上
  • .net 本地程序集加载因 CAS 策略失败

    我们收到以下程序集加载错误 该程序集是从本地路径 C Program Files ASWorx Products ASWorx Bin 加载的 旧版本的二进制文件不存在问题 当我们通过电子邮件发送新的二进制文件时 就会出现此问题 构建设置未
  • Alpha 通道(PNG) 和 Golang 的问题

    我在 golang 中的图像遇到一个简单的问题 我正在用颜色绘制 png 图像 但结果不是我想要的 在 Alpha 值最低的像素中 绘制另一种颜色 我正在使用 alphaChannel false return new image with
  • Android 12 kiosk 模式 - 屏幕超时后 NFC 停止工作

    我有一些使用 Android Management API 并在 kiosk 模式下运行的设备 从 Android 10 gt Android 12 升级后 我遇到了有关 NFC 扫描的新问题 设备重新启动后 一切似乎工作正常 如果我通过按
  • Javascript:将 HTML 中的行动态添加到 IE 中的表格时出现问题

    我查看了其他一些问题 例如this one https stackoverflow com questions 812693 cant dynamically add rows to a table in ie但他们没有解决这个特定问题 当
  • Erlang/OTP 架构:SOAish 服务的 RESTful 协议

    让我们想象一下 我们有一个为披萨店设计和构建的订单处理系统 要求是 R1 系统应该与客户端和用例无关 这意味着系统可以由初始设计期间未考虑到的客户端访问 例如 如果披萨店决定其许多顾客稍后使用三星 Bada 智能手机 那么为 Bada OS
  • 更改纯 ruby​​ 中的时区(不是 Rails)

    我正在构建一个 Sinatra 站点 该站点具有混合 UTC PST 数据源 但将在 PST 中查看 所以我需要一种方法来轻松地将 Time 对象从 UTC 转换为 PST 没有 Rails 我无法访问Time zone in time z
  • 如何将值插入到MYSQL中的自动标识列中[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我想将值插入 mysql innod
  • Firebase 功能会话 Cookie 未在子域上定义

    我尝试让 Firebase 会话 Cookie 工作以在所有子域中保留一个身份验证 现在我有了子域名accounts mysite com我将云功能以及登录表单路由到其中 在那里注册后 我调用我的云功能 app get authentica
  • 使用 gnuplot 绘制轨迹

    我有一个数据文件 其移动点的位置采用以下格式 x1 y1 x2 y2 x3 y3 我希望在 gnuplot 中使用这些数据制作动画轨迹 我怎样才能做到这一点 我试过 do for i 1 20 plot temp dat every i u
  • Android 如何停止其他Activity中的AlarmManager

    我正在使用一个在 AlarmManager 重复创建的活动 A 中调用的服务 我的服务正在重复检查服务器的响应 当响应为 true 时 新的 Activity B 就会启动 现在 当活动 B 启动时 我想停止服务以及 AlarmManage
  • 实体框架代码优先 - 多对多 - 包括条件

    我有两个实体Store and Catalog 使用流畅的 Api 建立多对多关系 我想通过以下方式获得商店id所有目录的状态都等于 已发布 下面我尝试编写以下查询 但没有得到预期的结果 var store context Stores I
  • Powershell 不允许我打开 firebase CLI

    每次我输入命令 firebase login 时 Powershell 都不会让我打开 firebase 出现了问题 如何打开文件 ihc 以前用 powershell 打开 firebase 从来没有遇到过问题 现在我明白了在此输入图像描
  • clearInterval 在reactjs 中不起作用

    SetInterval 工作正常 但clearInterval 不起作用 查看我的代码 我有父类 Channel 和子类 Body 当调用 componentDidMount 时 在 body 内 然后我为函数刷新状态设置间隔 在刷新状态函
  • 使用管道在 bash 中划分的最佳方法?

    我只是在寻找一种简单的方法来除法 或提供其他数学函数 假设我有以下命令 find name mp4 wc l 如何获取 wc l 的结果并将其除以 3 我见过的例子不涉及重定向出 入 Using bc bc l lt lt lt scale
  • 如何将参数传递给 DbMigration.Sql() 方法

    使用实体框架迁移时 DbMigration基类有一个 Sql 方法 它接受匿名对象中的参数 http msdn microsoft com en us library system data entity migrations dbmigr
  • D3.js:如何在版本 4 中向直方图添加分布线

    Note 这个问题 https stackoverflow com questions 41248649 d3 js how to add distribution curves to histograms in version 4是关于c