代码之家  ›  专栏  ›  技术社区  ›  Toke Faurby

如何在networkx中获取色条。draw\u networkx?

  •  1
  • Toke Faurby  · 技术社区  · 6 年前

    我正在对关系图执行聚类,目前正在使用 networkx 要可视化结果,请执行以下操作:

    G = nx.from_numpy_matrix(X)
    layout = nx.fruchterman_reingold_layout(G)
    nx.draw_networkx(G, pos=layout, with_labels=True, node_color=predict, cmap=plt.cm.coolwarm, vmin=0, vmax=1)
    

    enter image description here

    有可能得到一个色条吗?简单使用 plt.colorbar() 给出错误:

    RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).

    而且在 documentation 。 我也愿意使用另一个可视化软件包,只要它与Python 3兼容。

    1 回复  |  直到 6 年前
        1
  •  5
  •   MaxU - stand with Ukraine    6 年前

    以下是基于空手道俱乐部图表的演示:

    import pandas as pd
    import networkx as nx    
    import matplotlib.pyplot as plt
    
    G = nx.karate_club_graph()
    
    df = (pd.DataFrame(list(G.degree), columns=['node','degree'])
            .set_index('node'))
    df['club'] = pd.Series({node:data['club']
                            for node,data in G.nodes(data=True)})
    df['color'] = df.groupby('club')['degree'].transform(lambda c: c/c.max())
    df.loc[df['club']=='Officer', 'color'] *= -1
    
    layout = nx.fruchterman_reingold_layout(G)
    vmin = df['color'].min()
    vmax = df['color'].max()
    cmap = plt.cm.coolwarm
    
    nx.draw_networkx(G, pos=layout, with_labels=True, node_color=df['color'],
                     cmap=cmap, vmin=vmin, vmax=vmax)
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=vmin, vmax=vmax))
    sm.set_array([])
    cbar = plt.colorbar(sm)
    

    结果:

    enter image description here