d3.js forcelayout没有显示来自python的数据在flask上

im9ewurl  于 2022-11-12  发布在  Python
关注(0)|答案(1)|浏览(97)

我试图从一个python代码中检索节点和链接,它已经有了它们的唯一性,并且是JSON的形式,但是当console.log在浏览器上显示数据时,我无法在屏幕上以forcelayout图形的形式查看它们。大概我不理解在javascript中调用的顺序,所以忍受我缺乏javascript知识。这里的任何帮助都是非常感谢的。
这是一个从画廊借来的例子,当然我篡改了d3.json部分。

<script>
var width = 960,
    height = 500;

//force = d3.layout.force().nodes(d3.values(ailments)).links(rels).size([width, height]).linkDistance(60).charge(-300).on("tick", tick).start();

var nodes = {};
var ailments = {} ; 
var rels = []; 
var force = d3.layout.force().size([width, height]).linkDistance(60).charge(-300).on("tick",tick); 
console.log('initiated force!! be with you !!'); 

d3.json("/getA", function(error, dataset){
    console.log('getA the function gets called now ... '); 
    ailments = dataset.nodes; 
    //ailments = dataset.nodes['nodes']; 
    //rels = dataset.links['links'] ; 
    rels = dataset.links; 
    console.log(ailments); 
    //console.log(nodes);
    console.log('relationships coming up..'); 
    console.log(rels); 
    force.start(); 
}); 

function tick() {
  path.attr("d", linkArc);
  circle.attr("transform", transform);
  text.attr("transform", transform);
}

force = d3.layout.force().nodes(d3.values(ailments)).links(rels).size([width, height]).linkDistance(60).charge(-300).on("tick", tick).start();
console.log("now i threw the graph out there"); 

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);
svg.append("defs").selectAll("marker")
    .data(["suit", "licensing", "resolved"])
  .enter().append("marker")
    .attr("id", function(d) { return d; })
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("orient", "auto")
    .attr("stroke", "black")
  .append("path")
    .attr("d", "M0,-5L10,0L0,5");

// Per-type markers, as they don't inherit styles.

// Use elliptical arc path segments to doubly-encode directionality.
var path = svg.append("g").selectAll("path")
    .data(force.links())
  .enter().append("path")
    .attr("class", function(d) { return "link " + d.type; })
    .attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var circle = svg.append("g").selectAll("circle")
    .data(force.nodes())
  .enter().append("circle")
    .attr("r", 6)
    .call(force.drag);

var text = svg.append("g").selectAll("text")
    .data(force.nodes())
  .enter().append("text")
    .attr("x", 8)
    .attr("y", ".31em")
    .text(function(d) { return d.name; });  

function linkArc(d) {
  var dx = d.target.x - d.source.x,
      dy = d.target.y - d.source.y,
      dr = Math.sqrt(dx * dx + dy * dy);
  return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}

function transform(d) {
  return "translate(" + d.x + "," + d.y + ")";
}

</script>

  • 正如我所说,我仍然不清楚这里的顺序,因为这是我第一次尝试javascript!

注意到python和flask标签被删除-我认为这是好的,因为我不认为有一个问题,下面的python代码发送此数据。仅供参考

@app.route("/getA")
def getA():
    print('get A gets called ...')
    db = get_db()    
    nodes = []
    rels = []
    ailment = []
    cure = []
    jlinks = {"links":[]}
    uniqueNodes = {"nodes":[]}
    sql    = "MATCH (a:Ailment) -[:SOLVED_BY]->(theCURE) return a as ailment, theCURE limit 5"
    with db as graphDB_Session:
        nodes = graphDB_Session.run(sql)
        print("output:")
        for node in nodes:
            #print(node)
            prepare_links(node, ailment, cure)

    for idx, value in enumerate(ailment):
        #print (ailment[idx], cure[idx])
        source = ailment[idx]['title']
        target = cure[idx]['title']
        y = {"source":source, "target":target, "type":"SOLVED_BY"}
        jlinks["links"].append(y)
        if (source not in (uniqueNodes["nodes"])):
            uniqueNodes["nodes"].append(source)
        if (target not in (uniqueNodes["nodes"])):
            uniqueNodes["nodes"].append(target)

    print(jlinks)
    print(uniqueNodes)

    return Response(dumps({"nodes": uniqueNodes, "links": jlinks}),mimetype="application/json")

def serialize_ailment(ailment):
    return {
        "title":ailment["title"]
    }
def serialize_cure(cure):
    return {
        "title":cure["title"]
    }

def prepare_links(node, ailment, cure):
    #ailment.append(serialize_ailment(node.value("ailment")))
    ailment.append(node.value("ailment"))
    #cure.append(serialize_cure(node.value("theCURE")))
    cure.append(node.value("theCURE"))

忍受一些不需要的代码,评论,因为我基本上已经尝试了几个变种。

5jdjgkvh

5jdjgkvh1#

两个错误...我想...

  1. json函数中的forcelayout调用来修复调用的顺序(如我上面提到的)。
    1.在Javascript中,从API调用到另一个数组对象中获取数组的方法也很混乱。
    rels =数据集.链接[“链接”];
    看起来很明显,但不知何故,我也搞砸了这一点。更新后的脚本,工作在我自己的数据终于这样-
d3.json("/getA", function(error, dataset){
console.log('getA the function gets called now ... '); 
ailments = dataset.nodes; 
rels = dataset.links["links"]; 
console.log(ailments); 
//console.log(nodes);
console.log('relationships coming up..'); 
console.log(rels); 
//links = [dataset.links]; 

rels.forEach(function(dink) {
    dink.source = nodes[dink.source] || (nodes[dink.source] = {name: dink.source});
    dink.target = nodes[dink.target] || (nodes[dink.target] = {name: dink.target});
    console.log('creating unique nodes gets called again'); 
});
console.log('relationships again ..'); 
console.log(rels); 

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);
svg.append("defs").selectAll("marker")
    .data(["suit", "licensing", "resolved"])
  .enter().append("marker")
    .attr("id", function(d) { return d; })
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("orient", "auto")
    .attr("stroke", "black")
  .append("path")
    .attr("d", "M0,-5L10,0L0,5");   

var force = d3.layout.force().nodes(d3.values(nodes)).links(rels).size([width, height]).linkDistance(60).charge(-300).on("tick", tick).start();
console.log('graph goes up only now'); 

force.on("tick", function(e) {
  path.attr("d", linkArc);
  circle.attr("transform", transform);
  text.attr("transform", transform);
}); 
var text = svg.append("g").selectAll("text")
    .data(force.nodes())
  .enter().append("text")
    .attr("x", 8)
    .attr("y", ".31em")
    .text(function(d) { return d.name; });

var path = svg.append("g").selectAll("path")
    .data(force.links())
  .enter().append("path")
    .attr("class", function(d) { return "link " + d.type; })
    .attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var circle = svg.append("g").selectAll("circle")
    .data(force.nodes())
  .enter().append("circle")
    .attr("r", 6)
    .call(force.drag);
circle.attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")";
});

而“提供”这些数据的python代码是这样的...

@app.route("/getA")
def getA():
    print('get A gets called ...')
    db = get_db()

    nodes = []
    ailment = []
    cure = []
    jlinks = {"links":[]}
    uniqueNodes = {"nodes":[]}
    sql    = "MATCH (a:Ailment) -[:SOLVED_BY]->(theCURE) return a as ailment, theCURE limit 5"
    with db as graphDB_Session:
        nodes = graphDB_Session.run(sql)
        print("output:")
        for node in nodes:
            #print(node)
            prepare_links(node, ailment, cure)

    counter = 0 
    for idx, value in enumerate(ailment):
        source = ailment[idx]['title']
        target = cure[idx]['title']
        y = {"source":str(source), "target":str(target), "type":"SOLVED_BY"}
        jlinks["links"].append(y)

        if source not in uniqueNodes["nodes"]:
            uniqueNodes["nodes"].append(source)
        if target not in uniqueNodes["nodes"]: 
            uniqueNodes["nodes"].append(target)

    print(jlinks)    
    print(uniqueNodes)

    return Response(dumps({"nodes": uniqueNodes, "links": jlinks}),mimetype="application/json")

从技术上讲,我还没有用完来自python函数的唯一节点,但那是另一天的事了:)感谢阅读。

相关问题