# 大致思路:有向图和无向图分开绘制,再合并呈一个图
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
# 创建有向图
g_directed = nx.DiGraph()
# 添加有向边
directed_edges = [("A","B"),("B", "C"), ("C", "D"), ("D", "F")]
g_directed.add_edges_from(directed_edges)
# 创建无向图
g_undirected = nx.Graph()
# 添加无向边
undirected_edges = [("A", "C"), ("B", "D"), ("D", "E")]
g_undirected.add_edges_from(undirected_edges)
# 创建带弧度的有向边的图
g_radian = nx.Graph()
# 添加带有弧度的边
radian_edges = [("A","G"),("G","H")]
g_radian.add_edges_from(radian_edges)
# 创建合并的图对象
g_combined_temp = nx.compose(g_directed, g_undirected)
g_combined = nx.compose(g_combined_temp, g_radian)
# 创建布局
layout = {
"A": (0, 0),
"B": (1, 1),
"C": (2, 0),
"D": (1, -1),
"E": (3, -1),
"F": (2, 1),
"G": (-2, 2),
"H": (-3, -2)
}
# 创建绘图对象
fig, ax = plt.subplots()
# 绘制有向图
nx.draw_networkx_edges(g_combined, pos=layout,ax=ax, edgelist=g_directed.edges(), edge_color='black', width=1)
# 绘制无向图
nx.draw_networkx_edges(g_combined, pos=layout, ax=ax, edgelist=g_undirected.edges(), edge_color='red', width=1)
# 绘制带有弧度的有向边
nx.draw_networkx_edges(g_combined, pos=layout, ax=ax, edgelist=g_radian.edges(),edge_color='blue',connectionstyle='arc3,rad=0.3')
# 添加边的文字说明(方法一)
edge_labels = {("A", "H"): "0.8"} # 边及其对应的标签
nx.draw_networkx_edge_labels(g_combined, pos=layout, edge_labels=edge_labels, ax=ax)
# 添加边的文字说明(方法二)
edge = ("G", "H") # 起始节点和结束节点
start = list(layout[edge[0]]) # 起始节点位置
end = list(layout[edge[1]]) # 结束节点位置
text_pos = (start[0] + end[0]) / 2, (start[1] + end[1]) / 2
ax.text(text_pos[0], text_pos[1], "0.12", ha='center', va='center')
node_colors = [1, 2, 3, 4, 5, 6, 7, 8] # 节点颜色列表,与节点一一对应
cmap = plt.cm.Blues # 颜色映射
# 绘制节点
nx.draw_networkx_nodes(g_combined, pos=layout, ax=ax, node_color=node_colors, cmap=cmap, node_size=300)
# 绘制标签
nx.draw_networkx_labels(g_combined, pos=layout, ax=ax, font_color='black')
#====================绘制无向弧线=========================
# 定义两个节点之间的弧线路径
start = list(layout["A"]) # 起始节点位置
end = list(layout["D"]) # 结束节点位置
control = [start[0], end[1]] # 控制点位置,控制弧线的形状
vertices = [start, control, end] # 点坐标列表
codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3] # 绘制命令列表
path = Path(vertices, codes)
# 创建弧线补丁对象
patch = patches.PathPatch(path, edgecolor='black', lw=2, facecolor='none')
ax.add_patch(patch)
# 定义两个节点之间的弧线路径
start = list(layout["A"]) # 起始节点位置
end = list(layout["H"]) # 结束节点位置
control = [start[0], end[1]] # 控制点位置,控制弧线的形状
vertices = [start, control, end] # 点坐标列表
codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3] # 绘制命令列表
path = Path(vertices, codes)
# 创建弧线补丁对象
patch = patches.PathPatch(path, edgecolor='black', lw=1, facecolor='none')
ax.add_patch(patch)
# 显示图形
plt.title("Graph with Directed and Undirected Edges")
plt.axis('off')
plt.show()
运行得到的效果图如下: