首页 > 解决方案 > 为networkx中的不同节点组绘制不同的颜色

问题描述

我正在尝试使用 python3 networkx 模块绘制网络。具体来说,就是为 3 组不同的节点分配颜色。

    # visualize DiGraph
    def show_plan(self):        
        G = nx.DiGraph()
        G.add_nodes_from(self.nodes)
        # add within-district edges to G
        for district in self.districts:
            G.add_edges_from(self.district_edges[district], 
                             color='black', weight=0.5)
        
        # define default colors and weights to edges of G
        colors = nx.get_edge_attributes(G, 'color').values()
        weights = nx.get_edge_attributes(G, 'weight').values()
        
        # include cut edges in dotted red style in a separate graph H
        H = nx.DiGraph()
        H.add_nodes_from(G)
        for edge in self.cut_edges:
            H.add_edge(*edge, color='r', weight=0.2)
        colors_cut = nx.get_edge_attributes(H, 'color').values()
        weights_cut = nx.get_edge_attributes(H, 'weight').values()
        
        # possibly assign colors to districts
        
        # draw nodes, node labels, district edges, and cut edges
        nx.draw_networkx_nodes(G, self.node_coordinates, label = True, 
                               node_size = 50, node_shape = 'o')
        nx.draw_networkx_labels(G, self.node_coordinates, font_size = 4)
        nx.draw_networkx_edges(G, self.node_coordinates, edge_color=colors,
                               width=list(weights), arrows = False,)
        nx.draw_networkx_edges(H, self.node_coordinates, 
                               edge_color = colors_cut,
                               width = list(weights_cut), arrows = False, 
                               style = 'dotted')
        
        # display the finished map
        plt.show()
        return


具体来说,我想将代码添加到上面写着“#possibly assign colours to districts”的地方

标签: python

解决方案


推荐阅读