Django视图中Networkx节点填充颜色不生效问题及解决
解决Networkx DiGraph节点填充颜色不生效的问题
在Django视图中使用Networkx生成有向图时,遇到一个问题:通过nx.set_node_attributes(G, fill_coloring, name="background")设置节点填充颜色完全没效果,但用nx.set_node_attributes(G, border_coloring, name="color")设置节点边框颜色却能正常工作。
问题原因
节点的填充颜色属性background生效的前提是,节点的style属性必须被设置为"filled"——默认情况下这个属性未开启,所以即使设置了填充颜色也不会显示。
解决方案
在设置节点颜色属性的逻辑中,为需要填充颜色的节点添加style="filled"属性:
nx.set_node_attributes(G, {e.customer_end.name: "filled"}, name="style")
修改后的完整代码示例
def index(request): filename = f'{datetime.now():%Y-%m-%d_%H-%M-%S}.png' save_path = 'static/app/master/routing/' completeName = os.path.join(save_path, filename) print(completeName) G = nx.DiGraph() routings = Customer_Routing.objects.all() end_customers = [] border_coloring = {} fill_coloring = {} # 收集需要设置填充样式的节点 filled_nodes = [] for e in routings: G.add_edge(e.customer_start.name, e.customer_end.name) if e.customer_end.end_customer == True: try: print(e.customer_end.customer_class.name) if e.customer_end.customer_class.name == "DIY": border_coloring[e.customer_end.name] = "#DAC85A" fill_coloring[e.customer_end.name] = "#FEF19C" filled_nodes.append(e.customer_end.name) except AttributeError: print(e.customer_end.name + " has no class.") ### 统一设置节点样式与颜色 nx.set_node_attributes(G, {node: "filled" for node in filled_nodes}, name="style") nx.set_node_attributes(G, border_coloring, name="color") nx.set_node_attributes(G, fill_coloring, name="background") A = to_agraph(G) A.draw(completeName, prog='dot') template = loader.get_template('index.html') context = { 'img': completeName, 'routing': routings, } return HttpResponse(template.render(context, request))
注:将需要填充的节点统一收集后批量设置样式,比在循环中多次调用nx.set_node_attributes效率更高。
内容的提问来源于stack exchange,提问作者Berik
相关产品推荐
相关产品推荐

