Given an existing networkx
graph
import networkx as nx
import numpy as np
np.random.seed(123)
graph = nx.erdos_renyi_graph(5, 0.3, seed=123, directed=True)
nx.draw_networkx(graph)
or
import networkx as nx
G = nx.path_graph(4)
nx.spring_layout(G)
nx.draw_networkx(G)
how can you draw a red circle on top of (in the same position as) one of the nodes, like the node labeled 1
?
To be able to draw a.networkx graph, each node needs to be assigned a position. By default, nx.spring_layout()
is used to calculate positions when calling nx.draw.networkx()
, but these positions aren't stored. They are recalculated each time the function is drawn, except when the positions are explicitly added as a parameter.
Therefore, you can calculate these positions beforehand, and then use these to plot circles:
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
import networkx as nx
import numpy as np
np.random.seed(123)
graph = nx.erdos_renyi_graph(5, 0.3, seed=123, directed=True)
pos = nx.spring_layout(graph)
nx.draw_networkx(graph, pos=pos)
ax = plt.gca()
for node_id, color in zip([1, 4], ['crimson', 'limegreen']):
ax.add_patch(plt.Circle(pos[node_id], 0.15, facecolor=to_rgba(color, alpha=0.2), edgecolor=color))
ax.set_aspect('equal', 'datalim') # equal aspect ratio is needed to show circles undistorted
plt.show()
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.