matplotlib和networkx的交互式图形

时间:2014-03-16 11:44:44

标签: python matplotlib networkx

我的问题如下:

我想用networkx和matplotlib绘制图形。在显示图形时,我的程序应该处理其他一些东西。所以我想出了matplotlib.pyplot.ion()函数来允许交互模式。

我的代码:

def print_graph(graph):
    """ prints the graph"""

    # stores the nodes and their name attributes in a dictionary
    nodes_names = nx.get_node_attributes(graph, "name")
    plt.ion()
    pos = nx.spring_layout(graph)

    # draw without labels, cuz it would label them with their adress, since we
    nx.draw(graph, pos, with_labels=False)

    # draw the label with the nodes_names containing the name attribute
    labels = nx.draw_networkx_labels(graph, pos, nodes_names)
    plt.show()

def setup_sending(graph, iteration):
"""method which handles sending messages in the network,
only call it once for sending sweet packages in a network"""
    print_graph(graph)

    ###some code doing calculations....

    raw_input('Press enter to continue')    

运行此功能并不真正有效。它会完成所有计算甚至打开一个图形窗口。但是这个应该显示图形的窗口正在处理某些东西并保持白色。按Enter键后退出程序。

那么有没有人知道如何让代码显示图形?


修改

 def setup_graph(laplacian):
""" this fucntion creates a graph object with the nodes and its edges
already correct initialized"""
    # this block adds the nodes to the graph and creates two dict
    # in order to label the graph correctly
    size = len(laplacian[0, :])
    my_graph = nx.Graph()
    for i in range(size):
        my_graph.add_node(Node(), name=str(i + 1))
    print(my_graph.nodes())
    # stores the nodes and their name attributes in a dictionary
    nodes_names = nx.get_node_attributes(my_graph, "name")
    # switches key and values--> thus names_nodes
    names_nodes = dict(zip(nodes_names.values(), nodes_names.keys()))

    # this block adds the edges between the nodes
    for i in range(0, size):
        for j in range(i + 1, size):
            if laplacian[i, j] == -1:
                node_1 = names_nodes[str(i + 1)]
                node_2 = names_nodes[str(j + 1)]
                my_graph.add_edge(node_1, node_2)

    return my_graph

Node()只是一个包含特定列表的对象

1 个答案:

答案 0 :(得分:0)

这对我有用:

import networkx as nx
import matplotlib.pyplot as plt

def print_graph(graph):
    """ prints the graph"""

    # stores the nodes and their name attributes in a dictionary
    nodes_names = nx.get_node_attributes(graph, "name")
    plt.ion()
    pos = nx.spring_layout(graph)

    # draw without labels, cuz it would label them with their adress, since we
    nx.draw(graph, pos, with_labels=False)

    # draw the label with the nodes_names containing the name attribute
    labels = nx.draw_networkx_labels(graph, pos, nodes_names)
    plt.show()

def setup_sending(graph):
    print_graph(graph)

    ###some code doing calculations....

    raw_input('Press enter to continue')

def main():
    G=nx.dodecahedral_graph()
    setup_sending(G)

if __name__ == '__main__':
    main()

所以,我认为您的问题可能是图表的大小。它有多大?它有多少个节点/边缘?