本文整理汇总了Python中networkx.draw_networkx方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.draw_networkx方法的具体用法?Python networkx.draw_networkx怎么用?Python networkx.draw_networkx使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.draw_networkx方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_reaction_network
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def plot_reaction_network(self, file_name=None):
"""Plot the reaction network present in the database."""
pathways = []
load_paths = self.load_pathways()
for path in load_paths:
for R in path[:2]:
for P in path[2:]:
if R and P:
pathways += [[R, P]]
network = nx.Graph(pathways)
plt.figure(figsize=(6, 6))
nx.draw_networkx(network)
plt.draw()
plt.axis('off')
if file_name:
plt.savefig(file_name)
plt.close()
示例2: plot_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def plot_graph(plt, G):
plt.title('num of nodes: '+str(G.number_of_nodes()), fontsize = 4)
parts = community.best_partition(G)
values = [parts.get(node) for node in G.nodes()]
colors = []
for i in range(len(values)):
if values[i] == 0:
colors.append('red')
if values[i] == 1:
colors.append('green')
if values[i] == 2:
colors.append('blue')
if values[i] == 3:
colors.append('yellow')
if values[i] == 4:
colors.append('orange')
if values[i] == 5:
colors.append('pink')
if values[i] == 6:
colors.append('black')
plt.axis("off")
pos = nx.spring_layout(G)
# pos = nx.spectral_layout(G)
nx.draw_networkx(G, with_labels=True, node_size=4, width=0.3, font_size = 3, node_color=colors,pos=pos)
示例3: draw_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def draw_graph(matrix, clusters, **kwargs):
"""
Visualize the clustering
:param matrix: The unprocessed adjacency matrix
:param clusters: list of tuples containing clusters as returned
by 'get_clusters'
:param kwargs: Additional keyword arguments to be passed to
networkx.draw_networkx
"""
# make a networkx graph from the adjacency matrix
graph = nx.Graph(matrix)
# map node to cluster id for colors
cluster_map = {node: i for i, cluster in enumerate(clusters) for node in cluster}
colors = [cluster_map[i] for i in range(len(graph.nodes()))]
# if colormap not specified in kwargs, use a default
if not kwargs.get("cmap", False):
kwargs["cmap"] = cm.tab20
# draw
nx.draw_networkx(graph, node_color=colors, **kwargs)
axis("off")
show(block=False)
示例4: plot_embedding2D
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def plot_embedding2D(node_pos, node_colors=None, di_graph=None, labels=None):
node_num, embedding_dimension = node_pos.shape
if(embedding_dimension > 2):
print("Embedding dimension greater than 2, use tSNE to reduce it to 2")
model = TSNE(n_components=2)
node_pos = model.fit_transform(node_pos)
if di_graph is None:
# plot using plt scatter
plt.scatter(node_pos[:, 0], node_pos[:, 1], c=node_colors)
else:
# plot using networkx with edge structure
pos = {}
for i in range(node_num):
pos[i] = node_pos[i, :]
if node_colors is not None:
nx.draw_networkx_nodes(di_graph, pos,
node_color=node_colors,
width=0.1, node_size=100,
arrows=False, alpha=0.8,
font_size=5, labels=labels)
else:
nx.draw_networkx(di_graph, pos, node_color=node_colors,
width=0.1, node_size=300, arrows=False,
alpha=0.8, font_size=12, labels=labels)
示例5: draw
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def draw(self):
"""
Draw a network graph of the employee relationship.
"""
if self.graph is not None:
nx.draw_networkx(self.graph)
plt.show()
示例6: display_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def display_graph(variables, relations):
"""
Display the variables and relation as a graph, using networkx and
matplotlib.
Parameters
----------
variables: list
a list of Variable objets
relations: list
a list of Relation objects
"""
graph = as_networkx_graph(variables, relations)
# Do not crash if matplotlib is not installed
try:
import matplotlib.pyplot as plt
nx.draw_networkx(graph, with_labels=True)
# nx.draw_random(graph)
# nx.draw_circular(graph)
# nx.draw_spectral(graph)
plt.show()
except ImportError:
print("ERROR: cannot display graph, matplotlib is not installed")
示例7: overlay_skeleton_networkx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def overlay_skeleton_networkx(csr_graph, coordinates, *, axis=None,
image=None, cmap=None, **kwargs):
"""Draw the skeleton as a NetworkX graph, optionally overlaid on an image.
Due to the size of NetworkX drawing elements, this is only recommended
for very small skeletons.
Parameters
----------
csr_graph : SciPy Sparse matrix
The skeleton graph in SciPy CSR format.
coordinates : array, shape (N_points, 2)
The coordinates of each point in the skeleton. ``coordinates.shape[0]``
should be equal to ``csr_graph.shape[0]``.
Other Parameters
----------------
axis : Matplotlib Axes object, optional
The Axes on which to plot the data. If None, a new figure and axes will
be created.
image : array, shape (M, N[, 3])
An image on which to overlay the skeleton. ``image.shape`` should be
greater than ``np.max(coordinates, axis=0)``.
**kwargs : keyword arguments
Arguments passed on to `nx.draw_networkx`. Particularly useful ones
include ``node_size=`` and ``font_size=``.
"""
if axis is None:
_, axis = plt.subplots()
if image is not None:
cmap = cmap or 'gray'
axis.imshow(image, cmap=cmap)
gnx = nx.from_scipy_sparse_matrix(csr_graph)
# Note: we invert the positions because Matplotlib uses x/y for
# scatterplot, but the coordinates are row/column NumPy indexing
positions = dict(zip(range(coordinates.shape[0]), coordinates[:, ::-1]))
_clean_positions_dict(positions, gnx) # remove nodes not in Graph
nx.draw_networkx(gnx, pos=positions, ax=axis, **kwargs)
return axis
示例8: draw
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def draw(i):
cls1color = '#00FFFF'
cls2color = '#FF00FF'
pos = {}
colors = []
for v in range(34):
pos[v] = all_logits[i][v].numpy()
cls = pos[v].argmax()
colors.append(cls1color if cls else cls2color)
ax.cla()
ax.axis('off')
ax.set_title('Epoch: %d' % i)
nx.draw_networkx(nx_G.to_undirected(), pos, node_color=colors,
with_labels=True, node_size=300, ax=ax)
示例9: visualize
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def visualize(labels, g):
pos = nx.spring_layout(g, seed=1)
plt.figure(figsize=(8, 8))
plt.axis('off')
nx.draw_networkx(g, pos=pos, node_size=50, cmap=plt.get_cmap('coolwarm'),
node_color=labels, edge_color='k',
arrows=False, width=0.5, style='dotted', with_labels=False)
示例10: draw_and_save_topology
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def draw_and_save_topology(graph: nx.Graph, edge_labels: List[Dict[Tuple[str, str], str]]) -> None:
plt.figure(1, figsize=(12, 12))
pos = nx.spring_layout(graph)
nx.draw_networkx(graph, pos, node_size=1300, node_color='orange')
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels[0], label_pos=0.8)
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels[1], label_pos=0.2)
filename = "topology.png"
plt.savefig(filename)
logger.info("The network topology diagram has been saved to %r", filename)
示例11: plot_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def plot_graph(call_graph: nx.Graph, size: Tuple[int, int] = (10, 10)):
"""
Plot circular graph using matplotlib.
Parameters
----------
call_graph : nx.Graph
The graph to plot.
size : Tuple[int, int]
size of plot, default is(10,10)
"""
# if circos:
# c = CircosPlot(
# call_graph,
# node_color='degree',
# node_grouping='degree',
# node_order="degree",
# node_labels=True,
# fontsize="large",
# node_label_layout="rotation",
# figsize=(20,20)
# )
# c.draw()
# else:
pos = nx.circular_layout(call_graph)
nx.draw_networkx(call_graph, pos=pos)
plt.gcf().set_size_inches(size)
plt.show()
示例12: plot_embedding2D
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def plot_embedding2D(node_pos, node_colors=None, di_graph=None):
"""Function to plot the embedding in two dimension.
Args:
node_pos (Vector): High dimensional embedding values of each nodes.
node_colors (List): List consisting of node colors.
di_graph (Object): network graph object of the original network.
"""
node_num, embedding_dimension = node_pos.shape
if(embedding_dimension > 2):
print("Embedding dimension greater than 2, use tSNE to reduce it to 2")
model = TSNE(n_components=2)
node_pos = model.fit_transform(node_pos)
if di_graph is None:
# plot using plt scatter
plt.scatter(node_pos[:, 0], node_pos[:, 1], c=node_colors)
else:
# plot using networkx with edge structure
pos = {}
for i in range(node_num):
pos[i] = node_pos[i, :]
if node_colors is not None:
nx.draw_networkx_nodes(di_graph, pos,
node_color=node_colors,
width=0.1, node_size=100,
arrows=False, alpha=0.8,
font_size=5)
else:
nx.draw_networkx(di_graph, pos, node_color=node_colors,
width=0.1, node_size=300, arrows=False,
alpha=0.8, font_size=12)
示例13: visualize_provenance
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def visualize_provenance(self, labels=False):
if labels:
nx.draw_networkx(self.get_provenance().prov_graph())
else:
nx.draw(self.get_provenance().prov_graph())
plt.show()
示例14: plot_section
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def plot_section(self, i, n=0, plot_topo=False):
block = self.block_generate(i)
plt.imshow(block[:, n, :].T, origin="lower", cmap="YlOrRd")
if plot_topo:
pos_2d = {}
for key in self.topo_centroids[0].keys():
pos_2d[key] = [self.topo_centroids[0][key][0], self.topo_centroids[0][key][2]]
nx.draw_networkx(self.topo_graphs[i], pos=pos_2d)
示例15: nx_qubit_layout
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import draw_networkx [as 别名]
def nx_qubit_layout(graph: nx.Graph) \
-> Dict[cirq.Qid, Tuple[float, float]]:
"""Return a layout for a graph for nodes which are qubits.
This can be used in place of nx.spring_layout or other networkx layouts.
GridQubits are positioned according to their row/col. LineQubits are
positioned in a line.
>>> import cirq.contrib.routing as ccr
>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> # Clear plot state to prevent issues with pyplot dimensionality.
>>> plt.clf()
>>> g = ccr.xmon_device_to_graph(cirq.google.Foxtail)
>>> pos = ccr.nx_qubit_layout(g)
>>> nx.draw_networkx(g, pos=pos)
"""
pos: Dict[cirq.Qid, Tuple[float, float]] = {}
_node_to_i_cache = None
for node in graph.nodes:
if isinstance(node, cirq.GridQubit):
pos[node] = (node.col, -node.row)
elif isinstance(node, cirq.LineQubit):
# Offset to avoid overlap with gridqubits
pos[node] = (node.x, 0.5)
else:
if _node_to_i_cache is None:
_node_to_i_cache = {
n: i for i, n in enumerate(sorted(graph.nodes))
}
# Position in a line according to sort order
# Offset to avoid overlap with gridqubits
pos[node] = (0.5, _node_to_i_cache[node] + 1)
return pos