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)修改这个代码使得输出图形节点之间间隔合理能够看清
时间: 2024-02-14 07:29:41 浏览: 124
python数据分析与可视化 import pandas as pd import numpy as np import m
你可以尝试修改`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`值,你可以改变节点之间的距离,使得图形更易于观察。可以尝试不同的值来达到最合适的效果。
阅读全文