-
安装必要的Python库:
- 打开终端,安装NetworkX:
pip install networkx
- 安装Matplotlib:
pip install matplotlib
- 安装Seaborn:
pip install seaborn
- 安装Bokeh:
pip install bokeh
- 打开终端,安装NetworkX:
-
选择和准备数据集:
- 下载一个社会网络数据集,例如一个公司员工关系数据集。
- 确保数据格式适合Python处理,通常用字典或列表存储每个节点的信息,如名称、部门、职位等,以及节点之间的关系。
-
学习绘图库的基本用法:
-
NetworkX:
import networkx as nx # 创建网络实例 G = nx.Graph() # 添加节点 G.add_nodes_from([{"name": "A", "dept": "技术部"}, {"name": "B", "dept": "产品部"}]) # 添加边 G.add_edge("A", "B") # 绘图 nx.draw(G, with_labels=True) plt.show() -
Matplotlib + Seaborn:
import matplotlib.pyplot as plt import seaborn as sns # 创建节点列表 nodes = [ {"name": "A", "color": "red", "size": 10}, {"name": "B", "color": "blue", "size": 20}, {"name": "C", "color": "green", "size": 15} ] # 绘制节点图 plt.figure(figsize=(10, 5)) sns.kdeplot(x="size", y="size", hue="color", palette="Set2", legend=True) plt.scatter(x="size", y="size", c="color", s=100, alpha=.5) plt.xlabel("Size") plt.ylabel("Size") plt.title("Node Sizes") plt.show()
-
-
使用Bokeh绘制交互式图表:
from bokeh.plotting import output_notebook, show from bokeh.models import Circle, ColumnDataSource, Label from bokeh.palettes import Category3 # 创建数据源 data = ColumnDataSource(data={ "x": [1, 2, 3], "y": [2, 3, 4], "size": [5, 8, 13], "color": Category3[3]("A", "B", "C") }) # 绘制图表 p = output_notebook() p.scatter(x="x", y="y", size="size", legend_field="color", legend="color", fill_alpha=.6, color="color", tools="hover,pan,wheel_zoom,box_zoom,reset") p.add_tools() show() -
调整布局和样式:
- NetworkX:
options = { "node_colors": [color1, color2, ...], "node_size": 20, "edge_colors": [color], "edge_width": 2 } nx.draw(G, **options) - Matplotlib:
plt.rcParams.update({'axes.xmargin': 0, 'axes.ymargin': 0}) plt.tight_layout()
- NetworkX:
-
寻找并参考教程和示例代码:
- 网络X官方文档:https://networkx.org/documentation/
- Matplotlib官方教程:https://matplotlib.org/tutorials/introductory/plotting.html
- Seaborn教程:https://seaborn.pydata.org/tutorial.html
- Bokeh官方文档:https://bokeh.apache.org/docs/
-
编写代码并测试:
- 从简单的节点图开始,逐步添加功能,如边、布局调整等。
- 确保每次修改后测试代码,检查是否有错误或异常。
通过以上步骤,您可以逐步掌握使用Python绘制节点图的方法,并完成数据可视化项目,遇到问题时,不要怕,积极寻找解决方案,并不断练习。




