python networkx 导入CSV文件画关系网络图

本文介绍了如何利用Python的networkx库和matplotlib库创建并展示无向图和有向图。首先,从'node-8.csv'和'edge-8.txt'文件中读取数据来构建无向图,然后使用相同的方法从'node-8.csv'和'edge-9.txt'文件创建有向图,并添加权重。最后,通过networkx的draw_networkx函数绘制图形并显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


准备

Anaconda3中的Spyder
提前安装networkx、 matplotlib


提示:以下是本篇文章正文内容,下面案例可供参考

一、无向图

代码如下(示例):

import networkx as nx 
import matplotlib.pyplot as plt
import csv
 
with open('node-8.csv','rt') as csvfile:
	reader = csv.DictReader(csvfile)
	column = [row['b'] for row in reader]
#print (column)

 
 
 
edge = []
with open('edge-8.txt','r') as f:  
	data = f.readlines()  
	for line in data:
		#print (line)
		line = tuple(line.replace('\r','').replace('\n','').replace('\t','').split(','))
		edge.append(line)
#print (edge)

 
 
G = nx.Graph()
#G.add_nodes_from(id_tag)
G.add_edges_from(edge)
 
 
nx.draw_networkx(G,pos=nx.spring_layout(G),node_size=10,node_shape='o',width=0.3,style='solid',font_size=8) 


plt.show()

二、有向图

代码如下(示例):

import networkx as nx 
import matplotlib.pyplot as plt
import csv
 
with open('node-8.csv','rt') as csvfile:
	reader = csv.DictReader(csvfile)
	column = [row['b'] for row in reader]
#print (column)

edge = []
with open('edge-9.txt','r') as f:  
	data = f.readlines()  
	for line in data:
		#print (line)
		line = tuple(line.replace('\r','').replace('\n','').replace('\t','').split(','))
		edge.append(line)
#print (edge) 
 
G = nx.DiGraph()
#G.add_nodes_from(id_tag)
G.add_weighted_edges_from(edge)
 
nx.draw_networkx(G,pos=nx.spring_layout(G),node_size=20,node_shape='o',width=1,style='solid',font_size=8) 

plt.show()

参考链接

参考链接
http://blog.sciencenet.cn/blog-404069-337865.html
https://www.zhihu.com/question/59653147
https://segmentfault.com/a/1190000000527216
https://networkx.github.io/documentation/networkx-1.10/tutorial/tutorial.html#what-to-use-as-nodes-and-edges
【Python】Matplotlib画图(十)——基于networkx画关系网络图

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值