本文整理汇总了Python中networkx.spring_layout方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.spring_layout方法的具体用法?Python networkx.spring_layout怎么用?Python networkx.spring_layout使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.spring_layout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: apply_network_layout
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def apply_network_layout(G, layout='kamada_kawai', verbose=True):
if layout == 'kamada_kawai':
if verbose:
print('Applying the Kamada-Kawai network layout... (may take several minutes)')
pos = nx.kamada_kawai_layout(G)
elif layout == 'spring_embedded':
if verbose:
print('Applying the spring-embedded network layout... (may take several minutes)')
pos = nx.spring_layout(G, k=0.2, iterations=100)
for n in G:
G.nodes[n]['x'] = pos[n][0]
G.nodes[n]['y'] = pos[n][1]
return G
示例2: draw_wstate_tree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def draw_wstate_tree(svm):
import matplotlib.pyplot as plt
import networkx as nx
from networkx.drawing.nx_agraph import write_dot, graphviz_layout
G = nx.DiGraph()
pending_list = [svm.root_wstate]
while len(pending_list):
root = pending_list.pop()
for trace, children in root.trace_to_children.items():
for c in children:
G.add_edge(repr(root), repr(c), label=trace)
pending_list.append(c)
# pos = nx.spring_layout(G)
pos = graphviz_layout(G, prog='dot')
edge_labels = nx.get_edge_attributes(G, 'label')
nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels, font_size=8)
nx.draw_networkx_labels(G, pos, font_size=10)
plt.show()
示例3: draw_spring
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def draw_spring(G, **kwargs):
"""Draw networkx graph with spring layout.
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See hvplot.networkx.draw() for a description of optional
keywords, with the exception of the pos parameter which is not
used by this function.
Returns
-------
graph : holoviews.Graph or holoviews.Overlay
Graph element or Graph and Labels
"""
return draw(G, nx.spring_layout, **kwargs)
示例4: plot_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [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)
示例5: plot_network
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def plot_network(self, G, status, pos=None, nodelist=None, colordict={'S':'#009a80','I':'#ff2020', 'R':'gray'}, **nx_kwargs):
r'''
Plots the network in the axes self.networkx_ax. Nodes are colored according to their status.
if no ordered nodelist is provided, then the nodes are plotted so that 'I' nodes appear on top, while the order of the 'S' and 'R' nodes is random. When the network is very dense this highlights 'I' nodes and allows the final state to more accurately represent the proportion of nodes having each status.
'''
colorlist = []
if pos is None:
pos = nx.spring_layout(G)
if nodelist is None:
nodelist = list(G.nodes())
I_nodes = [node for node in nodelist if status[node] == 'I']
other_nodes = [node for node in nodelist if status[node]!='I']
random.shuffle(other_nodes)
nodelist = other_nodes + I_nodes
edgelist = list(G.edges())
else:
nodeset = set(nodelist)
edgelist = [edge for edge in G.edges() if edge[0] in nodeset and edge[1] in nodeset]
for node in nodelist:
colorlist.append(colordict[status[node]])
nx.draw_networkx_edges(G, pos, edgelist=edgelist, ax = self.network_axes, **nx_kwargs)
nx.draw_networkx_nodes(G, pos, nodelist = nodelist, node_color=colorlist, ax=self.network_axes, **nx_kwargs)
self.network_axes.set_xticks([])
self.network_axes.set_yticks([])
开发者ID:springer-math,项目名称:Mathematics-of-Epidemics-on-Networks,代码行数:26,代码来源:class_based_visualization.py
示例6: draw_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def draw_graph(graph, output):
"""If matplotlib is available, draw the given graph to output file"""
try:
layout = nx.spring_layout(graph)
metrics = {
(src, dst): data['metric']
for src, dst, data in graph.edges_iter(data=True)
}
nx.draw_networkx_edge_labels(graph, layout, edge_labels=metrics)
nx.draw(graph, layout, node_size=20)
nx.draw_networkx_labels(graph, layout,
labels={n: n for n in graph})
if os.path.exists(output):
os.unlink(output)
plt.savefig(output)
plt.close()
log.debug('Graph of %d nodes saved in %s', len(graph), output)
except:
pass
示例7: build_word_ego_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def build_word_ego_graph():
import networkx as nx
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
plt.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题)
from harvesttext import get_sanguo, get_sanguo_entity_dict, get_baidu_stopwords
ht0 = HarvestText()
entity_mention_dict, entity_type_dict = get_sanguo_entity_dict()
ht0.add_entities(entity_mention_dict, entity_type_dict)
sanguo1 = get_sanguo()[0]
stopwords = get_baidu_stopwords()
docs = ht0.cut_sentences(sanguo1)
G = ht0.build_word_ego_graph(docs,"刘备",min_freq=3,other_min_freq=2,stopwords=stopwords)
pos = nx.kamada_kawai_layout(G)
nx.draw(G,pos)
nx.draw_networkx_labels(G,pos)
plt.show()
G = ht0.build_entity_ego_graph(docs, "刘备", min_freq=3, other_min_freq=2)
pos = nx.spring_layout(G)
nx.draw(G, pos)
nx.draw_networkx_labels(G, pos)
plt.show()
示例8: plot_subgraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def plot_subgraph(self, region_start, region_stop, seq_name, neighbours=0):
"""
Return a plot of a sub-graph from a defined region with positions relative to some of the sequences.
:param region_start: Start position (bp)
:param region_stop: Stop position (bp)
:param seq_name: Sequence ID that the bp positions are relative to.
:param neighbours: Number of neighbours to be included. Currently testing, only 1 level available.
:return: Plots a netowrkx + matplotlib figure of the region subgraph.
"""
sub_graph = extract_region_subgraph(self, region_start, region_stop, seq_name, neighbours=neighbours)
pos = nx.spring_layout(sub_graph)
nx.draw_networkx_nodes(sub_graph, pos, cmap=plt.get_cmap('jet'), node_size=300)
nx.draw_networkx_labels(sub_graph, pos)
nx.draw_networkx_edges(sub_graph, pos, arrows=True)
plt.show()
示例9: AddLayoutPreCC
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def AddLayoutPreCC(g):
pos = ABPUtils.BuildLayoutArray(g)
if pos is None and len(g.nodes()) > 0:
pos = nx.spring_layout(g, k=1/math.sqrt(len(g.nodes())),
weight=math.sqrt(len(g.nodes())), scale=100, iterations=1000)
if pos is not None:
nx.set_node_attributes(g, 'x', dict(zip(g.nodes(), [pos[n][0] for n in g.nodes()])))
nx.set_node_attributes(g, 'y', dict(zip(g.nodes(), [pos[n][1] for n in g.nodes()])))
#starts = args.starts
#scores = {}
#scoreVals = []
#for idx in range(starts):
示例10: test_nx_cluster
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def test_nx_cluster(self):
g = nx.karate_club_graph()
coms = algorithms.louvain(g)
pos = nx.spring_layout(g)
viz.plot_network_clusters(g, coms, pos)
plt.savefig("cluster.pdf")
os.remove("cluster.pdf")
coms = algorithms.demon(g, 0.25)
pos = nx.spring_layout(g)
viz.plot_network_clusters(g, coms, pos, plot_labels=True, plot_overlaps=True)
plt.savefig("cluster.pdf")
os.remove("cluster.pdf")
示例11: test_smoke_int
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def test_smoke_int(self):
G = self.Gi
vpos = nx.random_layout(G)
vpos = nx.circular_layout(G)
vpos = nx.planar_layout(G)
vpos = nx.spring_layout(G)
vpos = nx.fruchterman_reingold_layout(G)
vpos = nx.fruchterman_reingold_layout(self.bigG)
vpos = nx.spectral_layout(G)
vpos = nx.spectral_layout(G.to_directed())
vpos = nx.spectral_layout(self.bigG)
vpos = nx.spectral_layout(self.bigG.to_directed())
vpos = nx.shell_layout(G)
if self.scipy is not None:
vpos = nx.kamada_kawai_layout(G)
vpos = nx.kamada_kawai_layout(G, dim=1)
示例12: test_empty_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def test_empty_graph(self):
G = nx.empty_graph()
vpos = nx.random_layout(G, center=(1, 1))
assert_equal(vpos, {})
vpos = nx.circular_layout(G, center=(1, 1))
assert_equal(vpos, {})
vpos = nx.planar_layout(G, center=(1, 1))
assert_equal(vpos, {})
vpos = nx.bipartite_layout(G, G)
assert_equal(vpos, {})
vpos = nx.spring_layout(G, center=(1, 1))
assert_equal(vpos, {})
vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
assert_equal(vpos, {})
vpos = nx.spectral_layout(G, center=(1, 1))
assert_equal(vpos, {})
vpos = nx.shell_layout(G, center=(1, 1))
assert_equal(vpos, {})
示例13: draw_adjacency_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def draw_adjacency_graph(adjacency_matrix,
node_color=None,
size=10,
layout='graphviz',
prog='neato',
node_size=80,
colormap='autumn'):
"""draw_adjacency_graph."""
graph = nx.from_scipy_sparse_matrix(adjacency_matrix)
plt.figure(figsize=(size, size))
plt.grid(False)
plt.axis('off')
if layout == 'graphviz':
pos = nx.graphviz_layout(graph, prog=prog)
else:
pos = nx.spring_layout(graph)
if len(node_color) == 0:
node_color = 'gray'
nx.draw_networkx_nodes(graph, pos,
node_color=node_color,
alpha=0.6,
node_size=node_size,
cmap=plt.get_cmap(colormap))
nx.draw_networkx_edges(graph, pos, alpha=0.5)
plt.show()
# draw a whole set of graphs::
示例14: malt_demo
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def malt_demo(nx=False):
"""
A demonstration of the result of reading a dependency
version of the first sentence of the Penn Treebank.
"""
dg = DependencyGraph("""Pierre NNP 2 NMOD
Vinken NNP 8 SUB
, , 2 P
61 CD 5 NMOD
years NNS 6 AMOD
old JJ 2 NMOD
, , 2 P
will MD 0 ROOT
join VB 8 VC
the DT 11 NMOD
board NN 9 OBJ
as IN 9 VMOD
a DT 15 NMOD
nonexecutive JJ 15 NMOD
director NN 12 PMOD
Nov. NNP 9 VMOD
29 CD 16 NMOD
. . 9 VMOD
""")
tree = dg.tree()
tree.pprint()
if nx:
# currently doesn't work
import networkx
from matplotlib import pylab
g = dg.nx_graph()
g.info()
pos = networkx.spring_layout(g, dim=1)
networkx.draw_networkx_nodes(g, pos, node_size=50)
# networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
networkx.draw_networkx_labels(g, pos, dg.nx_labels)
pylab.xticks([])
pylab.yticks([])
pylab.savefig('tree.png')
pylab.show()
示例15: plot
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import spring_layout [as 别名]
def plot(cg):
"""
Plot the call graph using matplotlib
For larger graphs, this should not be used, as it is very slow
and probably you can not see anything on it.
:param cg: A networkx call graph to plot
"""
from androguard.core.analysis.analysis import ExternalMethod
import matplotlib.pyplot as plt
import networkx as nx
pos = nx.spring_layout(cg)
internal = []
external = []
for n in cg.node:
if isinstance(n, ExternalMethod):
external.append(n)
else:
internal.append(n)
nx.draw_networkx_nodes(cg, pos=pos, node_color='r', nodelist=internal)
nx.draw_networkx_nodes(cg, pos=pos, node_color='b', nodelist=external)
nx.draw_networkx_edges(cg, pos, arrow=True)
nx.draw_networkx_labels(cg, pos=pos,
labels={x: "{} {}".format(x.get_class_name(),
x.get_name())
for x in cg.edge})
plt.draw()
plt.show()