【问题标题】:How to view a network generated with graph in python?如何在 python 中查看使用图形生成的网络?
【发布时间】:2019-02-10 09:13:54
【问题描述】:

我正在尝试生成网络并希望以图形方式查看它。

我正在使用一个列表来存储边缘信息。

我尝试了以下方法:

  from collections import defaultdict
class Graph(object):
    def __init__(self,connections):
        self.graph = defaultdict(set)
        self.addConnections(connections)

    def addConnections(self, connections):
        for node1, node2 in connections:
            self.addEdge(node1, node2)

    def addEdge(self, node1, node2):
        self.graph[node1].add(node2)

    def generateEdges(self): 
        edges = [] 
        for node in self.graph: 
            for neighbour in self.graph[node]: 
                edges.append((node, neighbour))
        self.edges = edges
        return edges

我正在尝试按如下方式查看图表:

import networkx as nx
import matplotlib.pyplot as plt
from graph import Graph
#create edges for first graph
graph1Edges = [('A','B'), ('A', 'D'), ('B', 'C'), ('C','D')]
graph1 = Graph(graph1Edges)
nx.draw(graph1.generateEdges())
plt.show()

但是,它不起作用,请建议我一种方法,因为我不想使用 networkx 包。

【问题讨论】:

    标签: python matplotlib networkx


    【解决方案1】:

    您尝试自己实现一个 Graph 并使用 networkx 显示它,而不是使用 networkx 的图形实现。这当然是不可能的,因为 nx.draw 需要一个 networkx 图。

    只需删除您的 Graph 实现并运行:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    edges = [('A', 'B'), ('A', 'D'), ('B', 'C'), ('C', 'D')]
    G = nx.Graph()
    G.add_edges_from(edges)
    nx.draw_networkx(G)
    plt.show()
    

    你会得到:

    【讨论】:

    • 是的,我想在不使用 networkx 包的情况下实现 Graph。请帮我解决这个问题
    • @Anil 但你没有提到你不想在你的问题中使用networkx
    • Networkx 绘图 API 仅适用于 networkx 图形。您可以将您的图表转换为 networkx 图表,或者直接使用一些绘图库(例如 matplotlib)。我不明白你想要达到什么目的。如果你仍然想使用networkx的绘图能力,但是改变了一些功能的实现,你也可以从networkx的Graph对象继承。
    • @zohar.kom,很抱歉没有在问题中提及。 是的,我不想使用 networkx 包,我在上面的问题中使用它只是为了尝试会发生什么。
    • 我不明白你想要达到什么目的。尝试阅读stackoverflow.com/help/how-to-ask 并尝试改进您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 2023-03-19
    • 2015-03-29
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多