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 中向直方图添加分布线 的相关文章

随机推荐

  • 使用 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