首页 > 解决方案 > Python networkx:显示一个节点的不同颜色

问题描述

我有一个子图列表,我想在一张图片中打印它,我在图 G 中添加了所有节点,但我想保留我的子图的信息,所以我给每个节点一个颜色,什么时候一个节点属于 2 个子图,它有 2 种颜色(3 属于 3,4 到 4,...)。

我的问题是在一张图片中显示节点及其所有颜色部分及其标签,当然是在赖特位置。我也想在图片中添加背景,并且这张图片不会出现在同一个情节中,但我会在同一个情节中显示它。

plt.figure(figsize=(22,18))

plt.imshow(background, origin='lower', cmap="binary", alpha=0.5)

nodes = nx.draw_networkx_nodes(G, pos=posi)
nx.draw_networkx_labels(G, pos=posi)

for node in G.nodes() :
   plt.pie([1]*pgm, center=posi[node], colors = [cmap(a) for a in colors[node]])
plt.show()
plt.close()

我受到在 Networkx 中将饼图创建为节点的启发

你知道我怎样才能给同一个节点不同的颜色并打印他们的标签,以及同一张图片中的背景吗?

标签: pythonpython-3.xmatplotlibgraphnetworkx

解决方案


enter image description here

def plotGraph2(List_sous_graphe, background) :
    SS_Graphe = renomme_ss_graphe(List_sous_graphe)
    for popu in range(0,1) :
        vim = 0
        vmax = len(SS_Graphe[popu])
        G = nx.Graph()
        colors_n = {}
        nb_col_n = {}
        size_n = {}
        for g in range(vim, vmax):
            taille_noeud = SS_Graphe[popu][g].graph['support']
            #couleur c'est g le numéro du graphe
            #color i the g number
            for n in SS_Graphe[popu][g].nodes():
                if not G.has_node(n) :
                    colors_n [n] = [g]
                    nb_col_n [n] = 1
                    size_n [n] = taille_noeud
                    G.add_node(n)
                    #print("N'a pas")
                else :
                    #print(SS_Graphe[popu][g].nodes[n])
                    colors_n [n].append(g)
                    nb_col_n [n] = nb_col_n [n] + 1

    max_value_n = max(nb_col_n.values())

    pgm = plus_grand_mutiple(max_value_n)

    #Pour chaque noeud
    for n in colors_n :
        tab[n] = []
        #Pour chaque couleur du noeud
        for i in range(0, nb_col_n[n]) :
            #On rajoute chaque couleur un nombre de fois pgm divisé par le nombre de couleur du noeud
            #print(pgm/nb_col_n[n])
            for j in range(0, int(pgm/nb_col_n[n])):
                #print(colors_n[n])
                tab[n].append(colors_n[n][i])

    a = np.array(list(tab.values()))
    maxes = np.max(a, axis=0)

    colors= {}
    for key, val in tab.items():
        colors[key] = list(np.array(val)/maxes)

    #Then the plt.pie that you see in the above message

You can see some nodes has 2 colors : https://media.discordapp.net/attachments/590286639075688449/723124784988160000/Capture_decran_de_2020-06-18_12-36-46.png?width=536&height=410 It's a part of my picture i just take a screenshot

Sorry for french comment in my code, sometimes i forgot to comment in english

My pictures


推荐阅读