Невозможно включить d3 в ноутбук Python Jupyter - PullRequest
0 голосов
/ 07 июня 2018

Я пытаюсь запустить следующий код в блокноте Jupyter, но не отображается схема сети на основе d3.Все, что я вижу, это небольшая коробка, но нет схемы сети.Было бы здорово, если бы кто-то мог помочь определить, что я делаю неправильно.Я на MacOS

Вот код:

Я экспортирую файл сына, а затем использую его для создания диаграммы d3 в блокноте Jupyter

from networkx.readwrite import json_graph
data = json_graph.node_link_data(G)
with open('graph.json', 'w') as f:
json.dump(data, f, indent=4)


%%html
<div id="d3-container"></div>
<style>
circle.node {stroke: #fff; stroke-width: 1.5px;}
line.link {stroke: #999; stroke-opacity: .6;}
</style>


%%javascript
// We load the latest version of d3.js from the Web.
require.config({paths: {d3: "https://d3js.org/d3.v5.min.js"}});
require(["d3"], function(d3) {

    // Parameter declaration, the height and width of our viz.
    var width = 300,
        height = 300;

    // Colour scale for node colours.
    var color = d3.scale.category10();

    // We create a force-directed dynamic graph layout.
    // D3 has number of layouts - refer to the documentation.
    var force = d3.layout.force()
        .charge(-120)
        .linkDistance(30)
        .size([width, height]);

    // We select the < div> we created earlier and add an 
    // SVG = Scalable Vector Graphics
    var svg = d3.select("#d3-container").select("svg")
    if (svg.empty()) {
        svg = d3.select("#d3-container").append("svg")
                    .attr("width", width)
                    .attr("height", height);
    }

    // We load the JSON network file.
    d3.json("graph.json", function(error, graph) {
        // Within this block, the network has been loaded
        // and stored in the 'graph' object.

        // We load the nodes and links into the force-directed
        // graph and initialise the dynamics.
        force.nodes(graph.nodes)
            .links(graph.links)
            .start();

        // We create a < line> SVG element for each link
        // in the graph.
        var link = svg.selectAll(".link")
            .data(graph.links)
            .enter().append("line")
            .attr("class", "link");

        // We create a < circle> SVG element for each node
        // in the graph, and we specify a few attributes.
        var node = svg.selectAll(".node")
            .data(graph.nodes)
            .enter().append("circle")
            .attr("class", "node")
            .attr("r", 5)  // radius
            .style("fill", function(d) {
                // We colour the node depending on the degree.
                return color(d.degree); 
            })
            .call(force.drag);

        // The label each node its node number from the networkx graph.
        node.append("title")
            .text(function(d) { return d.id; });



        // We bind the positions of the SVG elements
        // to the positions of the dynamic force-directed graph,
        // at each time step.
        force.on("tick", function() {
            link.attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });

            node.attr("cx", function(d) { return d.x; })
                .attr("cy", function(d) { return d.y; });
        });
    });
});

1 Ответ

0 голосов
/ 12 августа 2018

Здесь действуют несколько факторов.

d3v4 ++ не работает как d3v3, ​​поэтому, если вы вернетесь к d3v3, ​​это может сработать.

Загрузка d3v4 в сценарии с requirejs должна работать.то есть в ячейке:

<script type="text/javascript">

require.config({paths: {d3: "d3.min.js"}});
console.log(d3)
require(["d3"], function(d3) {
  console.log(d3.version);
});

И есть еще одна вещь, где браузер кэширует содержимое URI.Так что может случиться, если вам, протестировав различные типы d3, удастся случайно загрузить ноутбук jupyter с d3, результаты будут кэшированы.Вам придется явно закрыть и снова открыть браузер, чтобы проверить результаты.Если есть способ заставить блокнот jupyter отправлять заголовки без кэширования, это было бы замечательно, если бы вам не пришлось отправлять перенаправление браузера на прокси-сервер, который добавляет заголовки, указывающие отсутствие кэширования.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...