python-3.x 绘制带有彩色节点的图形

mcvgt66p  于 2023-07-01  发布在  Python
关注(0)|答案(1)|浏览(87)

我写了一段很短的代码(见下文),但是未着色的图和着色的图的布局不同。

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()

如果两个绘图(未着色和着色)具有相同的布局,则会更好。

yk9xbfzb

yk9xbfzb1#

我看到你可以像这样显式设置位置

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(1, 3)
G.add_edge(1, 5)
G.add_edge(2, 3)
G.add_edge(3, 4)
G.add_edge(4, 5)

# explicitly set positions
pos = {1: (0, 0), 2: (-1, 0.3), 3: (2, 0.17), 4: (4, 0.255), 5: (5, 0.03)}

options = {
    "font_size": 6,
    "node_size": 300,
    "node_color": "white",
    "edgecolors": "black",
    "linewidths": 1,
    "width": 1,
}

nx.draw_networkx(G, pos, **options)

# Set margins for the axes so that nodes aren't clipped
ax = plt.gca()
ax.margins(0.20)
plt.axis("off")
plt.show()

它产生(一致):

您可以将代码和数据转换为上述格式,以强制节点和边的位置。

相关问题