【问题标题】:Cannot get treemap to render with new JSON data无法使用新 JSON 数据呈现树状图
【发布时间】:2014-01-09 22:46:57
【问题描述】:

我在带有backbone.js 的应用程序中使用d3.js treemap。树形图使用第一个 JSOn 数据正确呈现,但随后使用不同 JSON 数据调用不会导致树形图重新呈现。

我的 HTML 如下所示:

<html>
<head>
    <title>Jenkins analytics</title>

    <!-- stylesheets -->
    <link rel="stylesheet" href="css/spa.css" type="text/css"/>
    <link rel="stylesheet" href="css/treemap.css" type="text/css"/>
</head>

<body>
    <nav>
        <form>
            <fieldset>
                <label for="chart">Chart:</label>
                <select id="chart" name="chart">
                    <option value="treemap" selected>Treemap</option>
                    <option value="motion">MotionChart</option>
                </select>
            </fieldset>
        </form>
        <form>
            <fieldset>
                <label for="period">Period:</label>
                <select id="period" name="period">
                    <option value="lastday" selected>Day</option>
                    <option value="lastweek">Week</option>
                    <option value="lastmonth">Month</option>
                </select>

                <label for="team">Team:</label>
                <select id="team" name="team">
                    <option value="all" selected>all</option>
                    <option value="spg">spg</option>
                    <option value="beacon">beacon</option>
                    <option value="disco">disco</option>
                </select>

                <label for="status">Status:</label>
                <select id="status" name="status">
                    <option value="" selected>all</option>
                    <option value="SUCCESS">success</option>
                    <option value="FAILURE">failure</option>
                    <option value="ABORTED">aborted</option>
                </select>
            </fieldset>
        </form>
        <form>
            <fieldset>
                <label for="duration">Duration</label>
                <input id="duration" type="radio" name="mode" value="size" checked />

                <label for="count">Count</label>
                <input id="count" type="radio" name="mode" value="count" />

                <label for="average">Average</label>
                <input id="average" type="radio" name="mode" value="avg" />
            </fieldset>
        </form>
    </nav>

    <div id="container" />

    <!-- Third party javascript -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js" charset="utf-8"></script>
    <script type="text/javascript" src="script/underscore/underscore.js" charset="utf-8"></script>
    <script type="text/javascript" src="script/backbone/backbone.js" charset="utf-8"></script>
    <script type="text/javascript" src="script/d3/d3.v3.js" charset="utf-8"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    <!-- Application javascript -->
    <script type="text/javascript" src="script/module.js"></script>

    <!-- Startup -->
    <script>
        var navview = new NavViewer();
    </script>
</body>
</html>

script/module.js 看起来像这样:

var NavViewer = Backbone.View.extend({
    el: 'nav',

    events: {
        "change #chart": "change_chart",
        "change #period": "change_period",
        "change #team": "change_team",
        "change #status": "change_status"
    },

    initialize: function() {
        console.log("NavViewer.initialize");
        this.d3view = new D3Viewer();
        this.active_view = this.d3view;
    },

    change_chart: function(e) {
        console.log("NavViewer.change_chart");
    },
    change_period: function(e) {
        var _period = $('#period').val();
        console.log("NavViewer.change_period to " + _period);
        this.active_view.load();
    },
    change_team: function(e) {
        var _team = $('#team').val();
        console.log("NavViewer.change_team to "+ _team);
        this.active_view.load();
    },
    change_status: function(e) {
        var _status = $('#status').val();
        console.log("NavViewer.change_status to " + _status);
        this.active_view.load();
    }
});

var JenkinsViewer = Backbone.View.extend({
    el: '#container',
    server: "http://192.168.1.100:5000",
    url_fragment: function() {
        var _period = $('#period').val();
        var _team = $('#team').val();
        var _status = $('#status').val();
        return "when=" + _period +
            (_team == "all" ? "" : ("&" + "team=" + _team)) +
            (_status == "" ? "" : ("&" + "status=" + _status));
    }
});

var D3Viewer = JenkinsViewer.extend({
    initialize: function() {
        this.margin = {top: 8, right: 0, bottom: 0, left: 0};
        this.width = 1200 - this.margin.left - this.margin.right;
        this.height = 800 - this.margin.top - this.margin.bottom - 60;
        this.container = d3.select(this.el);
        this.color = d3.scale.category20c();
        this.base_url = this.server + "/team_build";

        this.treemap = d3.layout.treemap()
            .size([this.width, this.height])
            .sticky(true)
            .value(function(d) { return d.size; });

        this.position = function() {
            this.style("left", function(d) { return d.x + "px"; })
                .style("top", function(d) { return d.y + "px"; })
                .style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; })
                .style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; });
        };

        /* style the container */
        this.container
            .style("position", "relative")
            .style("width", this.width + "px")
            .style("height", this.height + "px")
            .style("left", this.margin.left + "px")
            .style("top", this.margin.top + "px")
            .style("border", "1px solid black");

        /* tootlip is appended to container */
        this.tooltip = this.container.append("div")
            .attr('class', 'tooltip')
            .style("visibility", "hidden")
            .style("background-color", "#ffffff");

        this.load();
    },

    load: function() {
        var $container = this.container;
        var color = this.color;
        var treemap = this.treemap;
        var position = this.position;
        var tooltip = this.tooltip;
        var url = this.base_url + "?" + this.url_fragment();

        console.log("D3View.load: " + url);

        d3.json(url, function(error, root) {
            /* 'root' actually means the data retrieved by the xhr call */
            var node = $container.datum(root)
                .selectAll(".node")
                .data(treemap.nodes);

            node.enter().append("div")
                .attr("class", "node")
                .call(position)
                .style("background", function(d) { return d.children ? color(d.name) : null; })
                .text(function(d) { return d.children ? null : d.name; })
                .on("mouseover", function(d) {
                    tooltip.html(d.name + ": " + Math.floor(d.value))
                      .style("visibility", "visible");
                    this.style.cursor = "hand";
                })
                .on("mouseout", function(){
                    tooltip.style("visibility", "hidden");
                });

            d3.selectAll("input").on("change", function change() {
                var functions = {
                    count: function(d) { return d.count; },
                    size: function(d) { return d.size; },
                    avg: function(d) { return d.size / d.count; }
                };
                var value = functions[this.value];

                node
                    .data(treemap.value(value).nodes)
                .transition()
                    .duration(1500)
                    .call(position);
            });
        });

        return true;
    }
});

以下是我做过的事情:

我认为问题可能与粘性或没有呼叫 node.exit().remove() 有关。我试过修改这两个都没有成功。但是,要获得交互式客户端 UI,我想我需要使用 treemap.sticky(true)

我已确认每次访问 REST API 服务时都会得到不同的 JSON。我已经确认 container.datum().children 在调用之间的大小发生了变化,这对我来说是一个树图没有重新渲染的问题。

D3.js: How to handle dynamic JSON Data 看起来非常相关:

  • “值得一提的是,如果你已经有相同key的数据,d3.js会将数据存储在节点中,但仍会使用原始数据。”
  • “当我开始使用 d3.js 时,我认为渲染的数据会发生事件,并对我更改比例、域等做出反应。事实并非如此。你必须告诉 d3.js 更新当前的东西或者它将保留在那里,不同步。”
  • “我将 data() 的结果分配给一个变量,因为 enter() 只影响未绑定到节点的新数据。”

【问题讨论】:

  • 要明确:您是否对初始和后续数据调用使用相同的load() 函数?因为它只是在新元素上设置属性,而不是在具有更改数据的现有元素上设置属性。阅读此答案以获得更多分步说明:stackoverflow.com/a/20754006/3128209
  • @AmeliaBR:是的,我使用的是相同的load()。我将在这个星期六修复并发布更正的代码。但是,由于这显然是剪切和粘贴的代码,如果这个 D3 示例也使用了最佳实践,那就太好了。感谢您的帮助。
  • 不幸的是,那里的大多数示例和教程仅旨在演示代码的一个方面,而往往略过其他方面。所以他们展示了如何布置树形图,但没有展示如何更新它,或者类似的东西。如果你从非常简单的东西开始,然后一路向上,那么你就会知道你需要适应什么。但是大多数人想跳到复杂的可视化示例中,然后不知道代码哪里出了问题。
  • @hughdbrown,是的,真的,你复制代码的这个人为什么不准确地写出你需要的东西?给他发电子邮件,给他 $#$%,然后在他下次写一个他应该知道的例子时告诉他。对于您所做的一切,网络上应该有一个示例,以便您可以复制/粘贴,对吗?...
  • @VividD:感谢您花时间发布您的嘲讽。让我明确一点:我非常感谢操作系统开发人员以及他们在库和文档中所做的工作。我知道我的工作效率更高。由于您已经回答了 50 多个关于 d3.js 的问题,因此您和我一样知道这不仅仅是“某个人”。 D3 API 在渲染新数据的方式上非常不规则。例如,将其与 Google 的数据可视化进行比较。如果我正在编写示例代码,我会强调这一点。所以出于很多原因,我发现自己不同意你的观点。

标签: json d3.js treemap


【解决方案1】:

这是我最终在 load 方法中所做的:

load: function() {
    var $container = this.container;
    var color = this.color;
    var treemap = this.treemap;
    var position = this.position;
    var tooltip = this.tooltip;
    var url = this.base_url + "?" + this.url_fragment();

    console.log("D3View.load: " + url);

    d3.json(url, function(error, root) {
        var tooltip_mouseover = function(d) {
            tooltip.html(d.name + ": " + Math.floor(d.value))
              .style("visibility", "visible");
            this.style.cursor = "hand";
        };
        var tooltip_mouseout = function(){
            tooltip.style("visibility", "hidden");
        };
        var background_color = function(d) { return d.children ? color(d.name) : null; };
        var text_format = function(d) { return d.children ? null : d.name; };

        /*
         * Refresh sticky bit
         * https://github.com/mbostock/d3/wiki/Treemap-Layout
         * "Implementation note: sticky treemaps cache the array of nodes internally; therefore, it
         * is not possible to reuse the same layout instance on multiple datasets. To reset the
         * cached state when switching datasets with a sticky layout, call sticky(true) again."
         */
        treemap.sticky(true);

        /* 'root' actually means the data retrieved by the xhr call */
        var nodes = $container.datum(root)
            .selectAll(".node")
            .data(treemap.nodes);

        var enter = nodes.enter().append("div")
            .attr("class", "node")
            .call(position)
            .style("background", background_color)
            .text(text_format)
            .on("mouseover", tooltip_mouseover)
            .on("mouseout", tooltip_mouseout);

        var exit = nodes.exit().remove();

        var update = nodes.style("background", background_color)
            .call(position)
            .text(text_format);

        d3.selectAll("input").on("change", function change() {
            var functions = {
                count: function(d) { return d.count; },
                size: function(d) { return d.size; },
                avg: function(d) { return d.size / d.count; }
            };
            var value = functions[this.value];

            $container.selectAll(".node")
                .data(treemap.value(value).nodes)
            .transition()
                .duration(1500)
                .call(position);
        });
    });

有两个重要的变化:

  1. 重置树状图粘滞位
  2. 对新的/缺失的/更改的节点/数据使用进入/退出/更新选择

还请注意,enter 节点具有添加类 nodediv 的副作用,并且 exitupdate 节点不引用该 div 类——除非它们在创建nodes。如果在这些位置对 node-class 添加进一步的选择,您的选择将为空,exitupdate 代码将为无操作。

感谢AmeliaBR 发表了非常有用的评论,其中包含指向她撰写的 SO 答案的链接。

其他有用的读物​​:

【讨论】:

  • 很高兴您弄明白了,感谢您回来发布您的解决方案并为其他人提供良好的参考。更新过程是一个很容易混淆的过程,但是一旦你完全理解了它,它就会变成自动的,很容易忘记一开始它是多么的混乱!
猜你喜欢
  • 2014-04-05
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2019-11-05
  • 2017-01-15
  • 2018-11-21
  • 2021-03-27
  • 1970-01-01
相关资源
最近更新 更多