简体   繁体   中英

NetworkX extra labels when drawing graph with subset of nodes and edges

I found a problem that I have not been able to reproduce. I am currently working with a MultiDiGraph that I want to show only a portion of, the problem is that, when shown, I do not see only the nodes and edges that I selected, but also all of the labels in the graph.

I tried to recreate the error with something simple, as my original code is way to complex to explain.

import networkx as nx
import matplotlib.pyplot as plt
%matplotlib inline

gr = nx.MultiDiGraph()
gr.add_nodes_from(["192.168.1.1","192.168.1.2","192.168.1.3","192.168.1.4","192.168.1.5" ])
gr.add_edge("192.168.1.1", "192.168.1.2", key=1)
gr.add_edge("192.168.1.1", "192.168.1.3", key=2)
gr.add_edge("192.168.1.1", "192.168.1.4", key=3)
gr.add_edge("192.168.1.1", "192.168.1.5", key=4)
gr["192.168.1.1"]["192.168.1.2"][1]["color"] = 'b'
gr["192.168.1.1"]["192.168.1.3"][2]["color"] = 'b'
gr["192.168.1.1"]["192.168.1.4"][3]["color"] = 'b'
gr["192.168.1.1"]["192.168.1.5"][4]["color"] = 'b'

pos = nx.random_layout(gr)
plt.figure(figsize=(15, 7))

n=["192.168.1.1","192.168.1.2","192.168.1.3","192.168.1.4"]
e=[["192.168.1.1", "192.168.1.2", 1], ["192.168.1.1", "192.168.1.3", 2], 
   ["192.168.1.1", "192.168.1.4", 3]]
colors = [gr[u][v][k]["color"] for u, v, k in e]

nx.draw_networkx(gr, with_labels=True, edge_color=colors, nodelist=n, edgelist=e)

This is the image I get, as expected: Functioning But in my code I get something like this (fraction of result): Error

Does anybody has any idea why it does that?

Found a solution myself for this, in case it happens to someone else, you can just draw nodes, edges and labels separately.

import networkx as nx
l = {node: node for node in n}

nx.draw_networkx_nodes(G, pos=pos, node_color='black', alpha=0.9, node_size=60, nodelist=n)
nx.draw_networkx_edges(G, pos=pos, edge_color=colors, edgelist=e)
nx.draw_networkx_labels(G, pos=pos, font_size=8, font_color='black', labels=l)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM