绘图边缘权重在networkx Python 3中无法正常工作

时间:2019-04-13 08:59:39

标签: python-3.x networkx

我的边缘和体重数据是这样的: {{0,1):7,(0,2):3,(1,4):6,(1,2):1,(1,3):2,(2,3):2,( 3,4):4}

但是我得到了这样的图像。边缘权重显示错误。我想念什么?

enter image description here

这里0-> 1的权重为7,但显示为2。这是怎么回事?

我尝试了以下代码:

<script>
$(document).ready(function(){
    jQuery.each($('.textpost img'), function(){
        var img = $(this);
        var imgid = $(this).attr('src');

        $.ajax({
            url: 'inc/fn/imgfetch.php?i='+imgid,
            success: function(data) {
                var imgaddr = data;
                img.attr('src','med/img/posts/'+imgaddr);
            }
        });
    });
});
</script>

1 个答案:

答案 0 :(得分:1)

以这种方式清除代码:

import networkx as nx
from matplotlib import pyplot as plt

track =  {(0, 1): 7,
      (0, 2): 3,
      (1, 4): 6,
      (1, 2): 1,
      (1, 3): 2,
      (2, 3): 2,
      (3, 4): 4}


class Draw:
    def __init__(self):
        self.G=nx.Graph()

    def draw(self,node,track):
        # node data is a list containing nodes like [0,1,2,3,4]
        # track is edge and weight dict like {(0, 1): 7, (0, 2): 3, (1, 4): 6}
        [self.G.add_node(k) for k in node]
        [self.G.add_edge(k[0],k[1],weight=v) for k,v in track.items()]
        # label list data for the weight show
        labels = nx.get_edge_attributes(self.G,'weight')
        options = {'font_size':20,
                   'node_color':'red',
                   'label_pos':0.5,#(0=head, 0.5=center, 1=tail)
                   'node_size':1200,
                   'style':'solid',#(solid|dashed|dotted,dashdot)
                   'width':2}
        pos = nx.spring_layout(self.G)
        nx.draw(self.G,
                pos,
                with_labels=True,
                **options)

        nx.draw_networkx_edge_labels(self.G,
                                     pos,
                                    edge_labels=labels,
                                    **options)
        plt.savefig("graph.png")
        plt.show()


d = Draw()  
d.draw([*range(5)],track)

您会得到:

enter image description here