散点图的点在d3中不渲染

Dots of Scatterplot in d3 are not rendering

本文关键字:d3 散点图      更新时间:2023-09-26

我没有使用d3的经验,我只是偶尔使用Javascript和jQuery。

我试图在d3(和jQuery)中创建一个简单的散点图。滑块的作用是选择要绘制的数据集。我有一个JSON对象all_data,一个映射列表。对于列表中的每个映射,我分别使用"SI""F1"列表作为x和y值。

当滑动条移动时,我调用plotData()函数,参数为一个整数,表示all_data中数据集的索引(因此plotData(5)将绘制all_data中的第六个数据集)。

现在,由于某种原因,绘图轴构造得很好,但数据点没有绘制出来。我试图通过放置console.log(data)和来调试代码function (d,i) { console.log(d); return x(d['SI'])查看代码中的相关部分(参见注释行)。data对象包含函数中所有点的数据。问题似乎是在g.selectAll("scatter-dots")部分之后出现的。我怀疑对绘制"点"的函数的最后调用没有被调用,但我不知道为什么。

我的问题是:我如何修复我的代码,使数据点被添加到情节?任何其他关于编码,设计或性能改进的建议都非常受欢迎-在这里学习。

EDIT:我使用自定义d3。from GitHub

var all_data = [{"REGRESSION_Y": [ list_of_floats ], "F1": [ list_of_floats ], "SI": [ list_of_floats ], "f+": some_float_val }
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3 Test</title>
        <link rel="stylesheet" href="d3/d3-slider-master/d3.slider.css" />  
        <link rel="stylesheet" href="plot.css" />  
        <script type="text/javascript" src="jquery/jquery-3.1.1.min.js"></script>
        <script type="text/javascript" src="d3/d3.v3.min.js"></script>
        <script type="text/javascript" src="json_data.js"></script>
        <script type="text/javascript" src="d3/d3-slider-master/d3.slider.js"></script>
    </head>
    <body>
        <h2><span id="slider3text">Data points selected: 5</span></h2>
        <div id='container' style='width: 75%; height: 100%' class='centered'>
            <div id="plotfield" style='width: 100%; height: 90%'></div>
            <div id="slider3" style='height: auto'></div>
        </div>
    </body>
    <script type="text/javascript">

    d3.select('#slider3').call(d3.slider().axis(true).min( 5 ).max( all_data.length-1 ).step(1).on("slide", function(evt, value) {
                    d3.select('#slider3text').text("Data points selected: "  + value);
                    plotData(value)
              }));

        </script>

<script type="text/javascript">
function plotData(i) {
    var data = all_data[i]
    $("#plotfield").empty()
    var margin = {top: 50, right: 5, bottom: 80, left: 5}
      , width = $("#container").width() - margin.left - margin.right
      , height = $("#container").height() - margin.top - margin.bottom;
    var x = d3.scale.linear()
              .domain([0, d3.max(data, function(d) { return d['SI']; })])
              .range([ 0, width ]);
    var y = d3.scale.linear()
            .domain([0, d3.max(data, function(d) { return d['F1']; })])
            .range([ height, 0 ]);
    var chart = d3.select('#plotfield')
  .append('svg:svg')
  .attr('width', width + margin.right + margin.left)
  .attr('height', height + margin.top + margin.bottom)
  .attr('class', 'chart')
    var main = chart.append('g')
  .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
  .attr('width', width)
  .attr('height', height)
  .attr('class', 'main')   
    // draw the x axis
    var xAxis = d3.svg.axis()
  .scale(x)
  .orient('bottom');
    main.append('g')
  .attr('transform', 'translate(0,' + height + ')')
  .attr('class', 'main axis date')
  .call(xAxis);
    // draw the y axis
    var yAxis = d3.svg.axis()
  .scale(y)
  .orient('left');
    main.append('g')
  .attr('transform', 'translate(0,0)')
  .attr('class', 'main axis date')
  .call(yAxis);
   var g = main.append("svg:g"); 
    //console.log(data), this worked here
    g.selectAll("scatter-dots")
      .data(data)
      .enter().append("svg:circle")
          // I have tried function (d,i) { console.log(d); return x(d['SI']) 
          //in the below anonymous functions, but that doesn't yield an output, 
          //causing me to suspect that the functions are not executed.
          .attr("cx", function (d,i) { return x(d['SI']); } )
          .attr("cy", function (d) { return y(d['F1']); } )
          .attr("r", 3);
}

和CSS文件:

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}
body {
  font: 11px sans-serif;
}
.tooltip {
  position: absolute;
  width: 200px;
  height: 28px;
  pointer-events: none;
}
.axis line, .axis path {
    shape-rendering: crispEdges;
    stroke: black;
    fill: none;
}
circle {
    fill: steelblue;
}

从我看到的data[i]返回一个对象。这当然不是问题,但是d3方法enter()只支持数组。

这意味着当你使用enter()添加数据时,你不能有像d['f1']这样的东西。在使用它们之前将它们转换为数组可以解决这个问题,您可以使用d(数组条目)或i作为数组条目索引。

问题原来是var data = all_data[i]返回一个对象,而不是一个数组。我的一位同事提供了以下编辑以使其工作。(还更改了一些其他代码,以便在脚本中添加趋势线)。

<script type="text/javascript">
    function plotData(i) {
        // extracting data
        var data = all_data[i];
        var REGRESSION_Y = data.REGRESSION_Y;
        var F1 = data.F1;
        var SI = data.SI;
        // removing previous plot
        $("#plotfield").empty()
        // margins and spacings (slightly larger, y-axis was invinsible)
        var margin = {top: 50, right: 15, bottom: 80, left: 15}
        , width = $("#container").width() - margin.left - margin.right
        , height = $("#container").height() - margin.top - margin.bottom;
        var x = d3.scale.linear()
            .domain([0, d3.max(SI)])
            .range([ 0, width ]);
        var y = d3.scale.linear()
            .domain([0, d3.max(F1)])
            .range([ height, 0]);
        var chart = d3.select('#plotfield')
            .append('svg:svg')
            .attr('width', width + margin.right + margin.left)
            .attr('height', height + margin.top + margin.bottom)
            .attr('class', 'chart')
        var main = chart.append('g')
            .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
            .attr('width', width)
            .attr('height', height)
            .attr('class', 'main')   
        // draw the x axis
        var xAxis = d3.svg.axis()
            .scale(x)
            .orient('bottom');
        main.append('g')
            .attr('transform', 'translate(0,' + height + ')')
            .attr('class', 'main axis date')
            .call(xAxis);
        // draw the y axis
        var yAxis = d3.svg.axis()
            .scale(y)
            .orient('left');
        main.append('g')
            .attr('transform', 'translate(0,0)')
            .attr('class', 'main axis date')
            .call(yAxis);
        // append extra g part in svg and append to it
        var g = main.append("svg:g")
        // append the line
        g.append('line')
            .attr('x1', x(d3.min(SI)))//function(d, i) { return x(d[]) + i; })
            .attr('x2', x(d3.max(SI)))//(2)//function(d, i) { return y(d['REGRESSION_Y']); });
            .attr('y1', y(d3.min(REGRESSION_Y)))
            .attr('y2', y(d3.max(REGRESSION_Y)))
            .style('stroke', '#1B3277')
            .style('stroke-width','1')
        // append the dots
        g.selectAll("scatter-dots")
            .data(SI)
            .enter().append("svg:circle")
            .attr("cx", function (d,i) { return x(SI[i]); } )
            .attr("cy", function (d,i) { return y(F1[i]); } )
            .attr("r", 3);
    }

</script>