代码之家  ›  专栏  ›  技术社区  ›  sheldonzy

基于边宽度的matplotlib图例

  •  1
  • sheldonzy  · 技术社区  · 7 年前

    我拥有以下网络:

    enter image description here

    我想根据边的宽度创建一个图例。如下(数字不准确):

    enter image description here

    我应该创建一个新的子图,自己绘制线条和宽度吗?使用这种方法,我发现它非常复杂,因为有一些边缘情况需要处理,还有一些残酷的假设,比如要绘制的线的数量(尽管我想假设有8~10+条不同宽度的线是可以的)。

    import networkx as nx
    import matplotlib.pyplot as plt
    
    plt.subplot(1, 2, 1)
    graph = nx.Graph()
    graph.add_edge('a','b',weight=6)
    graph.add_edge('a','c',weight=2)
    graph.add_edge('c','d',weight=1)
    graph.add_edge('c','e',weight=7)
    graph.add_edge('c','f',weight=9)
    graph.add_edge('a','d',weight=3)
    edges = graph.edges()
    edges_weight_list = [graph[u][v]['weight'] for u,v in edges]
    n_nodes = graph.number_of_nodes()
    pos = nx.spring_layout(graph)
    nx.draw_networkx_edges(graph, pos, width = edges_weight_list)
    nx.draw_networkx_labels(graph, pos)
    mcp = nx.draw_networkx_nodes(graph, pos,
                                 node_color=list(range(n_nodes)),
                                 cmap='Blues')
    limits = plt.axis('off')  # turn of axis
    
    
    # width lines
    plt.subplot(1, 2, 2)
    edges_weight_list = sorted(edges_weight_list)
    for i, current_weight in enumerate(edges_weight_list):
        x=[0, 1]
        y=[i, i]
        plt.plot(x,y, linewidth=current_weight, color='black')
    
    plt.colorbar(mcp)
    limits = plt.axis('off')  # turn of axis
    plt.show()
    

    该图:

    enter image description here

    (显然,在一个真实的例子中,我不会迭代所有的行)。

    我使用的是python3.6、networkx2.2、matplotlib2.2.2。

    1 回复  |  直到 7 年前
        1
  •  0
  •   sheldonzy    7 年前

    最终,我创建了一个空列表,而不是绘制线条,然后手动添加文本 Line2D

    from matplotlib.lines import Line2D
    
    lines = []
    edges_weight_list = sorted(edges_weight_list)
    for i, width in enumerate(edges_weight_list):
        lines.append(Line2D([],[], linewidth=width, color='black'))
    
    legend2 = plt.legend(lines, edges_weight_list, bbox_to_anchor=(0, 0.5), frameon=False) 
    

    enter image description here