You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python绘制节点大小与边宽随重复次数变化的有向图

问题描述

我正在开展一项研究,需要绘制类似某PNAS论文中图2的有向图。主要使用Python,尝试过matplotlib、seaborn及NetworkX库,但未达到预期效果。

我的图节点为固定长度的二进制数(示例为5位,最长可达15位,可能产生大量节点),路径示例如下:

all_possible = [f"{i:>05b}" for i in range(2**5)] # 生成所有可能状态的代码
# 图的路径示例
path1 = ['start', '01101', '00001', '11000', '11100', '00010', '00100', 'end']
path2 = ['start', '10001', '00111', '01100', '01110', '10000', '11000', '00101', '11011', '01010', 'end']
path3 = ['start', '11100', '01001', '01100', '00011', '10111', '10000', '00001', 'end']
path4 = ['start', '01100', '01110', '11111', '11011', '10001', '11011', '11101', '00000', 'end']
path5 = ['start', '10001', '11100', '01101', '01001', '01000', '00101', '11001', '00101', '11100', 'end']

所有路径均从start状态出发,到end状态结束,中间经过各类状态组合,例如path1的路径为start -> 01101 -> 00001 -> 11000 -> 11100 -> 00010 -> 00100 -> end。

我需要实现两个核心效果:

  • 当更多边指向某节点(如11100)时,节点变大或变色以体现访问量;
  • 当某条边(如01100 -> 01110)被多次遍历时,边宽增加以体现重复次数。

我尝试了以下NetworkX代码,但未得到预期结果:

def draw_complete_graph(all_graph_edges: list, fig_size: tuple = (50, 50), graph_img_name: str = "test_graph"):
    G = nx.MultiDiGraph()
    plt.figure(figsize=fig_size)
    for single_edge in all_graph_edges:
        G.add_edge(
            single_edge[0],
            single_edge[-1],
            weight=all_graph_edges.count(single_edge),
            width=all_graph_edges.count(single_edge),
        )
    width_list = list(nx.get_edge_attributes(G, "width").values())
    nx.draw(
        G,
        with_labels=True,
        node_shape="o",
        width=width_list,
        connectionstyle="arc3, rad = 0.1",
        nodelist=["start", "end"],
    )
    plt.savefig(graph_img_name)
    plt.close()

def get_all_edges(all_paths: list[list]) -> list:
    graph_edges = list()
    for single_path in all_paths:
        graph_edges.append((single_path[0], single_path[1]))
        for ix, node in enumerate(graph_edges[1:-2]):
            graph_edges.append((node, single_path[ix + 1]))
    return graph_edges

if __name__ == "__main__":
    edges = get_all_edges([path1, path2, path3, path4, path5])
    draw_complete_graph(edges)

请问Python 3能否实现类似论文中的图效果?若可以,需对现有代码做哪些修改?


内容的提问来源于stack exchange,提问作者Asif Iqbal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:59:59