【问题标题】:Python networkx : show diiferent colors for one nodePython networkx:显示一个节点的不同颜色
【发布时间】:2020-10-08 07:17:00
【问题描述】:

我有一个子图列表,我想将它打印在一张图片中,我在图 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()

我的灵感来自Creating piechart as nodes in Networkx

你知道如何给同一个节点赋予不同的颜色并打印它们的标签,以及同一张图片中的背景吗?

【问题讨论】:

    标签: python python-3.x matplotlib graph networkx


    【解决方案1】:

    不是优雅或高效,但我认为这应该做你想要的

    # dummy graph
    df1 = pd.DataFrame({a:np.random.randint(0,8,100) for a in 'ab'})
    df2 = pd.DataFrame({a:np.random.randint(5,15,100) for a in 'ab'})
    df3 = pd.DataFrame({a:np.random.randint(12,20,100) for a in 'ab'})
    df4 = pd.DataFrame({a:np.random.randint(19,25,100) for a in 'ab'})
    
    graphs = []
    
    for i, df in enumerate([df1,df2,df3,df4]):
        G = nx.from_pandas_edgelist(df, source='a', target='b')
        for node in G.nodes:
            G.nodes[node]['part_of'] = []
        graphs.append(G.copy())
    
    F = nx.Graph()
    for G in graphs:
        F = nx.compose(F,G)
    
    
    # actual answer
    
    for node in F.nodes():
        for i, G in enumerate(graphs):        
            if node in G.nodes():
                F.nodes[node]['part_of'].append(i)
    
    pos = nx.spring_layout(F)
    
    fig = plt.figure(figsize=(10,10))
    cmap=plt.cm.viridis
    
    nx.draw_networkx_edges(F, pos=pos,)
    
    for node in F.nodes():
        part_of = list(set(F.nodes[node]['part_of']))
        w = plt.pie(
            [1]*len(part_of),
            center= pos[node],
            colors=[cmap(q/len(graphs)) for q in part_of],
            radius=0.05,
        )
    
    plt.xlim(-2,2)
    plt.ylim(-2,2)
    

    【讨论】:

    • 我想给一个节点不同的颜色
    • 使用 nx.draw_networkx 的 node_color,你应该为每个节点只给一个颜色,一个节点一个。
    • 是的,但不是我想的那样,让我 2 分钟告诉你我的代码和一张图片,如果我的电脑允许我这样做的话
    • 是的,对不起,我做到了
    • 也许我应该使用类似的东西:stackoverflow.com/questions/49587251/…
    【解决方案2】:

    我有类似的东西:

    def plot3(List, background) :
    
        graphs = []
    
        for i, df in enumerate(List[0]):
            G = List[0][i]
            for node in G.nodes:
                G.nodes[node]['part_of'] = []
            graphs.append(G.copy())
    
    
        F = nx.Graph()
        for G in graphs:
            F = nx.compose(F,G)
        nx.draw(F)
        print(F.number_of_nodes(), F.number_of_edges())
        print(len(List[0]))
    
        for node in F.nodes():
            for i, G in enumerate(graphs):        
                if node in G.nodes():
                    F.nodes[node]['part_of'].append(i)
    
        pos = nx.spring_layout(F)
    
        fig = plt.figure(figsize=(10,10))
    
        nx.draw_networkx_edges(F, with_labels=False, node_size=50, pos=pos, alpha=.3)# node_color=colors,
    
        cmap=plt.cm.viridis
    
        for node in F.nodes():
            part_of = list(set(F.nodes[node]['part_of']))
            w = plt.pie(
                [1]*len(part_of),
                center= pos[node],
                colors=[cmap(q/len(graphs)) for q in part_of],
                radius=0.05,
            )
    
        return 1
    
    

    【讨论】:

      【解决方案3】:

      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
      
      

      你可以看到一些节点有 2 种颜色: https://media.discordapp.net/attachments/590286639075688449/723124784988160000/Capture_decran_de_2020-06-18_12-36-46.png?width=536&height=410 这是我图片的一部分,我只是截图

      对不起,我的代码中有法语评论,有时我忘了用英语评论

      【讨论】:

      • 我为每个节点创建了一个包含 n 种颜色的表,如果节点应该有一种颜色,则 n 种颜色相同,如果应该有 2 种颜色,则一半是 1 种颜色,第二部分是其他颜色
      猜你喜欢
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多