我正在尝试使用 Networkx Dograph 和 matplotlib 创建图形,这是我的代码
def draw(self):
# Create a directed graph object
G = nx.DiGraph()
# Set node colors
node_colors = []
for tx in self.transactions.values():
#print("batch numer", self.num_batches)
if tx.txid == '1':
node_colors.append('orange') # orange for tips
elif tx.txid == '0' and self.current_batch == 0:
node_colors.append('grey') # gray for first transaction
elif tx in self.tips:
node_colors.append('grey') # gray for tips
else:
node_colors.append('blue') # blue for other nodes
# Get node positions and heights
pos = {}
heights = {}
for tx in self.transactions.values():
if tx.txid == '0':
pos[tx.txid] = (0, 0)
heights[tx.txid] = 0
else:
max_height = max(heights[parent_txid] for parent_txid in tx.parent_txids)
pos[tx.txid] = (max_height + 1, len(heights))
heights[tx.txid] = max_height + 1
# Add edges to the graph
for tx in self.transactions.values():
for parent_txid in tx.parent_txids:
G.add_edge(tx.txid, parent_txid)
# Draw the graph
plt.figure(figsize=(10, 5))
nx.draw(G, pos=pos, with_labels=True, node_color=node_colors, node_size=1000, node_shape='s')
#plt.axis('equal')
plt.ylim(-1, len(heights))
plt.xlim(-1, max(heights.values()) + 1)
plt.show()
这是输出
墨水版本是我想要的,节点 0 应该在最左边的中间,后面的节点应该水平而不是垂直增长。目前,新节点水平增长,但也垂直增长。我试过玩 plt.ylim(-1, len(heights)) plt.xlim(-1, max(heights.values()) + 1) 但是无法修复它,如果有人能帮我修复它就太好了。如果问题不清楚,请告诉我。