jupyter操作:graph = nx.from_pandas_edgelist(df,source="from",target="to") nx.degree(graph)之后,怎么将输出结果degreeview前半段作为作为x,后半段值作为y做条形图
时间: 2024-02-27 11:58:21 浏览: 9
可以使用`matplotlib`库来画条形图,具体代码如下:
```
import matplotlib.pyplot as plt
# 生成 degreeview 对象
degree_view = nx.degree(graph)
# 将 degreeview 对象转换成列表
degree_list = list(degree_view)
# 拆分 degree_list 列表,将前半部分作为 x 轴,后半部分作为 y 轴
x = [x[0] for x in degree_list]
y = [x[1] for x in degree_list]
# 绘制条形图
plt.bar(x, y)
# 设置 x 轴标签
plt.xlabel('Node')
# 设置 y 轴标签
plt.ylabel('Degree')
# 显示图形
plt.show()
```
其中,`degree_view` 是`nx.degree()`方法的返回值,即一个`degreeview`对象;`degree_list` 是将`degree_view`对象转换成列表的结果,即一个包含元组的列表;`x` 和 `y` 则是将`degree_list`列表拆分成两个列表,分别作为条形图的 x 轴和 y 轴数据。最后使用`plt.bar()`方法绘制条形图,并使用`plt.xlabel()`和`plt.ylabel()`方法设置 x 轴和 y 轴标签,最后使用`plt.show()`方法显示图形。
相关问题
如果不用创建新图,而是根据之前通过代码G = nx.from_pandas_edgelist(df, 'source', 'target','weight', create_using = nx.DiGraph())已导入的数据计算,应该怎么修改呢
如果你已经通过`nx.from_pandas_edgelist`方法将数据导入为图,那么可以直接使用该图进行计算,而无需创建新图。你可以按照以下方式修改代码:
```python
import networkx as nx
def calculate_yi(graph):
yi_values = {}
for node in graph.nodes:
yi = 0
for neighbor in graph.neighbors(node):
wij = graph[node][neighbor]['weight']
si = graph.nodes[node]['strength']
yi += (wij / si) ** 2
yi_values[node] = yi
return yi_values
# 假设你已经通过nx.from_pandas_edgelist方法导入了图数据为G
# 添加节点的强度属性
G.nodes[1]['strength'] = 1.2
G.nodes[2]['strength'] = 0.9
G.nodes[3]['strength'] = 1.5
G.nodes[4]['strength'] = 1.0
# 计算所有yi值
yi_values = calculate_yi(G)
print(yi_values)
```
在这个修改的代码中,我们假设你已经通过`nx.from_pandas_edgelist`方法将数据导入为了图`G`。然后,我们在图的节点上添加了强度属性,并调用`calculate_yi`函数计算所有的yi值。最后,我们打印输出了所有的yi值。请确保在运行代码之前,已经正确导入了图数据。
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`值,你可以改变节点之间的距离,使得图形更易于观察。可以尝试不同的值来达到最合适的效果。