javascript - Mysql to JSON to D3js no Visual... "class"识别错误

标签 javascript json d3.js circle-pack

D3 新手...

我正在尝试复制 simple example但是我的数据来自mysql。由于我将我的列重命名为“名称”和“大小”,因此应该很容易过渡。我相信 !d.children; 行/项目限制了要处理的数据,或者我的代码有误。

如何将类添加到现有的 .json



我需要删除哪些代码才能使现有的 .json 正常工作?

<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var diameter = 960,
    format = d3.format(",d"),
    color = d3.scale.category20c();

var bubble = d3.layout.pack()
    .sort(null)
    .size([diameter, diameter])
    .padding(1.5);

var svg = d3.select("body").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
    .attr("class", "bubble");

d3.json("json.php", function(error, root) {
  var node = svg.selectAll(".node")
      .data(bubble.nodes(classes(root))
      .filter(function(d) { return !d.children; }))
.enter().append("g")
  .attr("class", "node")
  .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

  node.append("title")
      .text(function(d) { return d.className + ": " + format(d.value); });

  node.append("circle")
      .attr("r", function(d) { return d.r; })
      .style("fill", function(d) { return color(d.packageName); });

  node.append("text")
      .attr("dy", ".3em")
      .style("text-anchor", "middle")
      .text(function(d) { return d.className.substring(0, d.r / 3); });
});

// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
  var classes = [];

  function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
    else classes.push({packageName: name, className: node.name, value: node.size});
  }

  recurse(null, root);
  return {children: classes};
}

d3.select(self.frameElement).style("height", diameter + "px");

</script>

json.php

<?php
$username = "homedbuser"; 
$password = "homedbuser";   
$host = "localhost";
$database="homedb";

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

$myquery = "
SELECT  `name`, `size` FROM  `lists`
";
    $query = mysql_query($myquery);

    if ( ! $myquery ) {
        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);
?>

此外,我认为脚本中的 root 有错误(假设是数据)。我将继续根据我的研究更新代码,直到有响应为止。

最佳答案

您正在尝试的图表要求数据采用分层格式。对于您给出的查询,数据似乎没有层次结构。

我使用了 csv 数据,但没关系,我已经为您在链接中提供的图表提供了我使用的格式。

编写您的 SQL 查询以获取以下格式的数据并使用 d3.json 并导入 php 文件,一切都应该工作正常。

我已经粘贴了所有代码和示例数据。

这可能对您有所帮助。任何问题也请提供示例数据。

数据:


    name,size
    level1,23
    level1,23
    level1,23
    level1,23
    level1,23
    level1,23
    level1,23
    level1,23
    level1,23
    level2,23
    level2,23
    level2,23
    level2,23
    level2,23
    level2,23
    level2,23
    level2,23
    level2,23

用于转换为层次结构的函数:


    d3.csv("data.csv", function(root) {

                var newData = { name :"root", children : [] },
                    levels = ["name"];

                // For each data row, loop through the expected levels traversing the output tree
                root.forEach(function(d){
                    // Keep this as a reference to the current level
                    var depthCursor = newData.children;
                    // Go down one level at a time
                    levels.forEach(function( property, depth ){

                        // Look to see if a branch has already been created
                        var index;
                        depthCursor.forEach(function(child,i){
                            if ( d[property] == child.name ) index = i;
                        });
                        // Add a branch if it isn't there
                        if ( isNaN(index) ) {
                            depthCursor.push({ name : d[property], children : []});
                            index = depthCursor.length - 1;
                        }
                        // Now reference the new child array as we go deeper into the tree
                        depthCursor = depthCursor[index].children;
                        // This is a leaf, so add the last element to the specified branch
                        if ( depth === levels.length - 1 ) depthCursor.push({ name : d.name, size : d.size });
                    });
                });

                //Print what we've got
                d3.select('body').append('pre')
                           .text(JSON.stringify(newData, null, '  '));
            })

结合这两个功能的脚本:


    var diameter = 960,
        format = d3.format(",d"),
        color = d3.scale.category20c();

    var bubble = d3.layout.pack()
        .sort(null)
        .size([diameter, diameter])
        .padding(1.5);

    var svg = d3.select("body").append("svg")
        .attr("width", diameter)
        .attr("height", diameter)
        .attr("class", "bubble");

    d3.json("yourphpfile.php", function(error, data) {
        var root = { name :"root", children : [] },
                    levels = ["name"];

                // For each data row, loop through the expected levels traversing the output tree
                data.forEach(function(d){
                    // Keep this as a reference to the current level
                    var depthCursor = root.children;
                    // Go down one level at a time
                    levels.forEach(function( property, depth ){

                        // Look to see if a branch has already been created
                        var index;
                        depthCursor.forEach(function(child,i){
                            if ( d[property] == child.name ) index = i;
                        });
                        // Add a branch if it isn't there
                        if ( isNaN(index) ) {
                            depthCursor.push({ name : d[property], children : []});
                            index = depthCursor.length - 1;
                        }
                        // Now reference the new child array as we go deeper into the tree
                        depthCursor = depthCursor[index].children;
                        // This is a leaf, so add the last element to the specified branch
                        if ( depth === levels.length - 1 ) depthCursor.push({ name : d.name, size : d.size });
                    });
                });


      var node = svg.selectAll(".node")
          .data(bubble.nodes(classes(root))
          .filter(function(d) { return !d.children; }))
        .enter().append("g")
          .attr("class", "node")
          .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

      node.append("title")
          .text(function(d) { return d.className + ": " + format(d.value); });

      node.append("circle")
          .attr("r", function(d) { return d.r; })
          .style("fill", function(d) { return color(d.packageName); });

      node.append("text")
          .attr("dy", ".3em")
          .style("text-anchor", "middle")
          .text(function(d) { return d.className.substring(0, d.r / 3); });
    });

    // Returns a flattened hierarchy containing all leaf nodes under the root.
    function classes(root) {
      var classes = [];

      function recurse(name, node) {
        if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
        else classes.push({packageName: name, className: node.name, value: node.size});
      }

      recurse(null, root);
      return {children: classes};
    }

    d3.select(self.frameElement).style("height", diameter + "px");

关于javascript - Mysql to JSON to D3js no Visual... "class"识别错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995049/

相关文章:

c# - 将 JsonMediaTypeFormatter 应用于 Json

php - 无法使用javascript访问json文件

javascript - 在 web View 中放置 svg 对象

javascript - 如何防止 promise 在没有箭头功能的情况下丢失上下文

javascript - 选择字段 OnChange,使 <tr> 显示/隐藏,最初显示但一旦消失,无法重新显示

javascript - Magento - 无法在管理员中上传产品图片

javascript - 在 angularjs 中处理 json 响应(来自 PHP 和 mysql)

javascript - 使用 window.document.href 时如何不重定向

javascript - 使用 selectAll 获取特定于某个组的 svg 元素

动态创建图形的 Javascript 库?