How to show d3.js circle pack graph in a Rails application?

﹥>﹥吖頭↗ 提交于 2019-12-09 13:58:04

问题


I have been trying for long to make this : http://bl.ocks.org/mbostock/4063269#flare.json example work in my sample Rails app to learn about d3.js. But, I am getting hard time to make it work.

I put the following code in my index.html.erb file :

<script type="text/javascript">

    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("assets/data/flare.json", 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>

I put the flare.json file inside my app/assets/data directory. But, it seems like the javascript can not load the flare.json file from that location. I am just not sure how to make this work :( How to specify the location of the json file so that the javascript can load it and the code works? Any suggestion would be much much helpful.


回答1:


Instead of loading the json file via d3.json, I rendered its contents on the javascript file and used a variable to store it.

var root = <%= render partial: 'controller_view/flare.json', formats: [:json] %>;


来源:https://stackoverflow.com/questions/15983935/how-to-show-d3-js-circle-pack-graph-in-a-rails-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!