我写了一段很短的代码(见下文),但是未着色的图和着色的图的布局不同。
G=[1,0,0,0,1,0,0,1,1,1] # Define the graph. Upper right half-triangle of the adjacency matrix)
#-----------
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import random
l=len(G)
import math
nNodes=round(1/2 +math.sqrt(2*l+1/2))
adjMatrix=np.zeros((nNodes, nNodes))
ij=0
for i in range(nNodes):
for j in range(i+1,nNodes):
adjMatrix[i][j]=G[ij]
ij=ij+1
# Create a graph from the adjacency matrix and draw
Gdraw = nx.from_numpy_matrix(adjMatrix)
# Draw the graph
nx.draw_networkx(Gdraw, with_labels=True, node_color='lightgrey', )
plt.show()
# Draw the colored graph
Color=random.sample(range(nNodes), nNodes)
print(Color)
nx.draw_networkx(Gdraw, with_labels=True, node_color=Color)
plt.show()
如果两个绘图(未着色和着色)具有相同的布局,则会更好。
1条答案
按热度按时间yk9xbfzb1#
我看到你可以像这样显式设置位置:
它产生(一致):
您可以将代码和数据转换为上述格式,以强制节点和边的位置。