dougou5852 2016-02-13 16:14
浏览 66
已采纳

d3 - 如何在php脚本中使用计数器中的值

When you use a counter in an sql query in a php script connecting a database to d3, how do you call that counter to use the values stored in it from d3? For instance I have the query

SELECT `ID_to`, count(*) as counter from `citations` group by `ID_to` ORDER BY counter desc

Now I want to call counter from d3 and use its values to scale my y axis on my scatterplot. It doesnt seem to work when I just use it as if it were a column in the table ie:

var yValue = function(d) { return d.counter;}, // data -> value
yScale = d3.scale.linear().range([height, 0]), // value -> display
yMap = function(d) { return yScale(yValue(d));}, // data -> display
yAxis = d3.svg.axis().scale(yScale).orient("left");

d3.json("connection2.php", function(error, data){
data.forEach(function(d) {
    d['ID_from'] =+d['ID_from']; 
    d['counter'] = +d['counter'];

     console.log(d);
    })      

How do I access these counter values and use them in d3?? Any help is much appreciated I am getting very frustrated with myself going around in circles. The error I'm getting is :

Error: Invalid value for <circle> attribute cy="NaN"

EDIT:: Here is my php script:

<?php
$username = "xxx"; 
$password = "xxx";   
$host = "xxx";
$database="xxx";

$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);

$myquery = "SELECT `ID_to`, count(*) as `counter` from `citations` group by `ID_to`";

$query = mysql_query($myquery);

if ( ! $query ) {
    echo mysql_error();
    die;
}

$data = array();

for ($x = 0; $x < mysql_num_rows($query); $x++) {
    $data[] = mysql_fetch_assoc($query);
}

echo json_encode($data);     

mysql_close($server);
?>

I have ran it in my browser and it returns correct results.

  • 写回答

4条回答 默认 最新

  • dongzhong5573 2016-02-13 17:33
    关注

    The reason for your cy="NaN" is that you've not assigned a domain to your scale. While the range is the pixel space of your chart, the domain is the value space (the range of values) in your data. You can use d3.extent, to get the min/max of your dataset:

    yScale = d3.scale
      .linear()
      .range([height, 0])
      .domain(
        d3.extent(data, function(d){ return d.counter; })
      );
    

    I suggest you take the time to create a small reproducible example of your problem. I attempted to do that below, but everything works fine.

    Also, In this statement d3.json("connection2.php", function(error, data){, you don't handle the error, are you sure your JSON's returning correctly:

    d3.json("connection2.php", function(error, data){
       if (error) throw error;
    
       console.log(data);
    

    What does that output?


    <!DOCTYPE html>
    <meta charset="utf-8">
    <style>
      body {
        font: 10px sans-serif;
      }
      
      .axis path,
      .axis line {
        fill: none;
        stroke: #000;
        shape-rendering: crispEdges;
      }
      
      .dot {
        stroke: #000;
      }
    </style>
    
    <body>
      <script src="//d3js.org/d3.v3.min.js"></script>
      <script>
      
        var margin = {
            top: 20,
            right: 20,
            bottom: 30,
            left: 40
          },
          width = 960 - margin.left - margin.right,
          height = 500 - margin.top - margin.bottom;
    
        var yValue = function(d) {
            return d.counter;
          }, // data -> value
          yScale = d3.scale.linear().range([height, 0]), // value -> display
          yMap = function(d) {
            return yScale(yValue(d));
          }, // data -> display
          yAxis = d3.svg.axis().scale(yScale).orient("left");
          
        var xValue = function(d){
          return d.ID_from;
        },
        xScale = d3.scale.linear().range([0, width]), // value -> display
        xMap = function(d) {
            return xScale(xValue(d));
          }, // data -> display
        xAxis = d3.svg.axis().scale(xScale).orient("bottom");
    
        var svg = d3.select("body").append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    
    
        var data = [{
          'ID_from': 1,
          'counter': parseInt(Math.random() * 100)
        }, {
          'ID_from': 2,
          'counter': parseInt(Math.random() * 100)
        }, {
          'ID_from': 3,
          'counter': parseInt(Math.random() * 100)
        }, {
          'ID_from': 4,
          'counter': parseInt(Math.random() * 100)
        }, {
          'ID_from': 5,
          'counter': parseInt(Math.random() * 100)
        }, {
          'ID_from': 6,
          'counter': parseInt(Math.random() * 100)
        }, {
          'ID_from': 7,
          'counter': parseInt(Math.random() * 100)
        }, {
          'ID_from': 8,
          'counter': parseInt(Math.random() * 100)
        }];
    
        data.forEach(function(d) {
          d.ID_from = +d.ID_from;
          d.counter = +d.counter;
        });
    
        xScale.domain([d3.min(data, xValue) - 1, d3.max(data, xValue) + 1]);
        yScale.domain([d3.min(data, yValue) - 1, d3.max(data, yValue) + 1]);
    
        svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis);
    
        svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
          .append("text");
    
        svg.selectAll(".dot")
          .data(data)
          .enter().append("circle")
          .attr("class", "dot")
          .attr("r", 3.5)
          .attr("cx", xMap)
          .attr("cy", yMap);
    
      </script>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数