import networkx as nx import matplotlib.pyplot as plt # 创建有向图 G = nx.DiGraph() # 添加状态节点 G.add_node('q0') G.add_node('q1') G.add_node('q2') G.add_node('q3') # 添加起始状态 G.add_edge('', 'q0') # 添加终止状态 G.add_edge('q2', '') # 添加转移边 G.add_edge('q0', 'q1', label='a') G.add_edge('q0', 'q3', label='b') G.add_edge('q1', 'q2', label='a') G.add_edge('q1', 'q3', label='b') G.add_edge('q2', 'q2', label='a') G.add_edge('q2', 'q2', label='b') G.add_edge('q3', 'q2', label='a') G.add_edge('q3', 'q3', label='b') # 绘制图形 pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, node_size=1000) nx.draw_networkx_edges(G, pos, width=1) nx.draw_networkx_edge_labels(G, pos, font_size=14, edge_labels={(u, v): d['label'] for u, v, d in G.edges(data=True)}) nx.draw_networkx_labels(G, pos, font_size=18, font_family='sans-serif') plt.axis('off') plt.show()
时间: 2023-08-14 07:02:45 浏览: 293
这是一个绘制DFA图形的Python程序,它使用了networkx和matplotlib.pyplot库。这个程序定义了一个有向图G,它包含了DFA的各个状态和转移边。在绘制图形的过程中,使用spring_layout函数为每个节点指定位置,使用draw_networkx_nodes和draw_networkx_edges函数绘制节点和边,使用draw_networkx_edge_labels函数为每条边添加标签,使用draw_networkx_labels函数为每个节点添加标签。最后,使用plt.show函数显示绘制的图形。
相关问题
import pandas as pd import numpy as np import networkx as nx import matplotlib.pyplot as plt # 读取Excel文件中的邻接矩阵 adjacency_matrix = pd.read_excel('output.xlsx', index_col=0) # 将邻接矩阵转换为numpy数组 adjacency_matrix = adjacency_matrix.to_numpy() # 创建有向图对象 G = nx.DiGraph(adjacency_matrix) def preprocess(G): p = 0 directedGraph = nx.DiGraph() for u in G.nodes(): for v in G.neighbors(u): if (v != u): propProb = G.number_of_edges(u, v) / G.degree(v) directedGraph.add_edge(u, v, pp=propProb) return directedGraph def simulate(G, seedNode, propProbability): newActive = True currentActiveNodes = seedNode.copy() newActiveNodes = set() activatedNodes = seedNode.copy() influenceSpread = len(seedNode) while newActive: for node in currentActiveNodes: for neighbor in G.neighbors(node): if neighbor not in activatedNodes: if G[node][neighbor]['pp'] > propProbability: newActiveNodes.add(neighbor) activatedNodes.append(neighbor) influenceSpread += len(newActiveNodes) if newActiveNodes: currentActiveNodes = list(newActiveNodes) newActiveNodes = set() else: newActive = False return influenceSpread def flipCoin(probability): return np.random.random() < probability # 可视化传播过程 def visualizePropagation(G, seedNode, propProbability): pos = nx.spring_layout(G) # 选择布局算法 labels = {node: node for node in G.nodes()} # 节点标签为节点名 colors = ['r' if node in seedNode else 'b' for node in G.nodes()] # 种子节点为红色,其他节点为蓝色 plt.figure(figsize=(10,6)) nx.draw_networkx_nodes(G, pos, node_color=colors) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos, labels) plt.title('Propagation Visualization') plt.show() # 示例用法 seedNode = [7,36,17] propProbability = 0.7 directedGraph = preprocess(G) influenceSpread = simulate(directedGraph, seedNode, propProbability) print("Influence Spread:", influenceSpread) visualizePropagation(directedGraph, seedNode, propProbability)修改这个代码使得输出图形节点之间间隔合理能够看清
你可以尝试修改`nx.spring_layout()`函数的参数,例如`k`,来调整节点之间的距离。这个参数控制着节点之间的斥力大小,较大的`k`值会使节点之间的距离增大,从而使得图形更容易观察。
下面是修改后的代码示例:
```python
# 可视化传播过程
def visualizePropagation(G, seedNode, propProbability):
pos = nx.spring_layout(G, k=0.5) # 调整k值来改变节点之间的距离
labels = {node: node for node in G.nodes()} # 节点标签为节点名
colors = ['r' if node in seedNode else 'b' for node in G.nodes()] # 种子节点为红色,其他节点为蓝色
plt.figure(figsize=(10,6))
nx.draw_networkx_nodes(G, pos, node_color=colors)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos, labels)
plt.title('Propagation Visualization')
plt.show()
# 示例用法
seedNode = [7,36,17]
propProbability = 0.7
directedGraph = preprocess(G)
influenceSpread = simulate(directedGraph, seedNode, propProbability)
print("Influence Spread:", influenceSpread)
visualizePropagation(directedGraph, seedNode, propProbability)
```
通过调整`k`值,你可以改变节点之间的距离,使得图形更易于观察。可以尝试不同的值来达到最合适的效果。
import pandas as pd import networkx as nx import matplotlib.pyplot as plt df = pd.read_excel(r"C:\Users\li'yi'jie\Desktop\运筹学网络规划数据.xlsx") edges = [] for i in range(len(df)): edge = { "id": df.loc[i, "边的编号"], "tail": df.loc[i, "边的尾节点"], "head": df.loc[i, "边的头节点"], "length": df.loc[i, "长度"], "capacity": df.loc[i, "容量"] } edges.append(edge) plt.figure(figsize=(10,8)) G = nx.DiGraph() for edge in edges: G.add_edge(edge["tail"], edge["head"], weight=edge["length"]) all_pairs = dict(nx.all_pairs_dijkstra_path_length(G)) pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True) labels = nx.get_edge_attributes(G, "weight") nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.3) plt.show()如何让生成的有向图两只箭头分开
可以使用 `nx.draw_networkx_edge_labels()` 函数的 `label_pos` 和 `font_size` 参数来调整边权重标签的位置和大小,从而避免标签与箭头重叠。同时,可以使用 `nx.draw_networkx_edges()` 函数的 `arrowsize` 参数来调整箭头大小。修改后的代码如下所示:
```
import pandas as pd import networkx as nx import matplotlib.pyplot as plt df = pd.read_excel(r"C:\Users\li'yi'jie\Desktop\运筹学网络规划数据.xlsx") edges = [] for i in range(len(df)): edge = { "id": df.loc[i, "边的编号"], "tail": df.loc[i, "边的尾节点"], "head": df.loc[i, "边的头节点"], "length": df.loc[i, "长度"], "capacity": df.loc[i, "容量"] } edges.append(edge) plt.figure(figsize=(10,8)) G = nx.DiGraph() for edge in edges: G.add_edge(edge["tail"], edge["head"], weight=edge["length"]) all_pairs = dict(nx.all_pairs_dijkstra_path_length(G)) pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True, arrowsize=20) labels = nx.get_edge_attributes(G, "weight") nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.3, font_size=12) plt.show()
```
运行后可以看到箭头和边权重标签已经分开,且箭头大小也被调整为了 20。您可以适当调整 `arrowsize` 参数的值,以达到最佳效果。
阅读全文