Python 如何使用加权邻接矩阵绘制边权重?

Python 如何使用加权邻接矩阵绘制边权重?,python,matplotlib,networkx,graph-theory,adjacency-matrix,Python,Matplotlib,Networkx,Graph Theory,Adjacency Matrix,我有一个问题,我有一个有向图的加权邻接矩阵C,所以C(j,I)=0,当j到I没有边时,如果C(j,I)>0,那么C(j,I)是边的权重 现在我想绘制有向图。手动添加边时有许多解决方案,例如,请参见此处: 但我想根据矩阵C绘制边和边权重;我是这样开始的: def DrawGraph(C): import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph(C) plt.figure(

我有一个问题,我有一个有向图的加权邻接矩阵C,所以C(j,I)=0,当j到I没有边时,如果C(j,I)>0,那么C(j,I)是边的权重

现在我想绘制有向图。手动添加边时有许多解决方案,例如,请参见此处:

但我想根据矩阵C绘制边和边权重;我是这样开始的:

def DrawGraph(C):

    import networkx as nx
    import matplotlib.pyplot as plt 


    G = nx.DiGraph(C)

    plt.figure(figsize=(8,8))
    nx.draw(G, with_labels=True)
这将绘制一个图,顶点上有标签,但没有边权重-而且我无法适应上链接的技术使其工作-那么我能做什么


我将如何更改节点大小和颜色?

使用networkx有多种方法可以做到这一点-以下是一个适合您需求的解决方案:

代码:

# Set up weighted adjacency matrix
A = np.array([[0, 0, 0],
              [2, 0, 3],
              [5, 0, 0]])

# Create DiGraph from A
G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)

# Use spring_layout to handle positioning of graph
layout = nx.spring_layout(G)

# Use a list for node_sizes
sizes = [1000,400,200]

# Use a list for node colours
color_map = ['g', 'b', 'r']

# Draw the graph using the layout - with_labels=True if you want node labels.
nx.draw(G, layout, with_labels=True, node_size=sizes, node_color=color_map)

# Get weights of each edge and assign to labels
labels = nx.get_edge_attributes(G, "weight")

# Draw edge labels using layout and list of labels
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels)

# Show plot
plt.show()
结果:

# Set up weighted adjacency matrix
A = np.array([[0, 0, 0],
              [2, 0, 3],
              [5, 0, 0]])

# Create DiGraph from A
G = nx.from_numpy_matrix(A, create_using=nx.DiGraph)

# Use spring_layout to handle positioning of graph
layout = nx.spring_layout(G)

# Use a list for node_sizes
sizes = [1000,400,200]

# Use a list for node colours
color_map = ['g', 'b', 'r']

# Draw the graph using the layout - with_labels=True if you want node labels.
nx.draw(G, layout, with_labels=True, node_size=sizes, node_color=color_map)

# Get weights of each edge and assign to labels
labels = nx.get_edge_attributes(G, "weight")

# Draw edge labels using layout and list of labels
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels)

# Show plot
plt.show()

使用完全相同的A,当我使用命令“G=nx.from_numpy_matrix(A,create_Using=nx.DiGraph)”时,我得到一个错误:“输入图形不是networkx图形类型”-可能缺少某种包吗?@Ivan如果在
nx.DiGraph
中添加括号,你会得到同样的错误吗?如下所示:
G=nx.from\u numpy\u矩阵(A,使用=nx.DiGraph()创建)
出色的工作!