本文整理汇总了Python中networkx.spring_layout函数的典型用法代码示例。如果您正苦于以下问题:Python spring_layout函数的具体用法?Python spring_layout怎么用?Python spring_layout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了spring_layout函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: draw_figures
def draw_figures(problem, clique_collection, probability):
"""
function to draw figure
:param problem: input problem
:param clique_collection: all collection lists of cliques
:param probability: input probability
:return: show and save the out figure from origin to k-cliques graph with probability
"""
pos = nx.spring_layout(problem.G)
pl.figure(1)
pl.title("original figure with probability {p}".format(p=probability))
nx.draw(problem.G, pos=pos)
nx.draw_networkx_labels(problem.G, pos, font_size=10, font_family='sans-serif')
pl.savefig("origin_with_prob_{p}.png".format(p=probability))
# pl.show()
for i in range(len(clique_collection)):
new_nodes = []
for n in problem.G.nodes():
for li in clique_collection[i]:
if n in li:
new_nodes.append(n)
subgraph = problem.G.subgraph(new_nodes)
pos = nx.spring_layout(problem.G)
pl.figure()
pl.title('{k} cliques with probability {p}'.format(k=i+3, p=probability))
nx.draw(subgraph, pos=pos)
nx.draw_networkx_labels(subgraph, pos, font_size=10, font_family='sans-serif')
pl.savefig("{k}_cliq_with_prob_{p}.png".format(k=i+3, p=probability))
开发者ID:WeiliangXing,项目名称:Facebook-Data-Mining,代码行数:31,代码来源:exp.py
示例2: paint_clusters
def paint_clusters(G1, G2, beacons_G1, beacons_G2, kmeans_labels1, kmeans_labels2):
accent_colors = brewer2mpl.get_map('Accent', 'qualitative',8).mpl_colors
plt.subplot(121)
plt.axis('off')
plt.title('$G_1$')
(labels, node_colors, node_sizes) = visualize_beacons(G1, beacons_G1)
clustered_colors = cluster_colors(G1, beacons_G1, kmeans_labels1, accent_colors)
pos = nx.spring_layout(G1, weight=None)
nx.draw_networkx_nodes(G1, pos, node_color=clustered_colors, node_size=node_sizes, font_size=18)
nx.draw_networkx_labels(G1, pos, font_size=17, labels=labels, font_color = '#262626')
nx.draw_networkx_edges(G1, pos, width=2, alpha=0.3)
plt.subplot(122)
plt.axis('off')
plt.title('$G_2$')
(labels, node_colors, node_sizes) = visualize_beacons(G2, beacons_G2)
clustered_colors = cluster_colors(G2, beacons_G2, kmeans_labels2, accent_colors)
pos2_init= {key:value for (key, value) in zip(beacons_G2,[pos[beacon] for beacon in beacons_G1])}
pos2 = nx.spring_layout(G2, weight=None, pos = pos2_init)
nx.draw_networkx_nodes(G2, pos=pos2, node_color=clustered_colors, node_size=node_sizes, font_size=18)
nx.draw_networkx_labels(G2, pos=pos2, font_size=17, labels=labels, font_color = '#262626')
nx.draw_networkx_edges(G2, pos=pos2, width=2, alpha=0.3)
开发者ID:harrymvr,项目名称:graph-isomorphism,代码行数:26,代码来源:graph_isomorphisms.py
示例3: test_scale_and_center_arg
def test_scale_and_center_arg(self):
G = nx.complete_graph(9)
G.add_node(9)
vpos = nx.random_layout(G, scale=2, center=(4,5))
self.check_scale_and_center(vpos, scale=2, center=(4,5))
vpos = nx.spring_layout(G, scale=2, center=(4,5))
self.check_scale_and_center(vpos, scale=2, center=(4,5))
vpos = nx.spectral_layout(G, scale=2, center=(4,5))
self.check_scale_and_center(vpos, scale=2, center=(4,5))
# circular can have twice as big length
vpos = nx.circular_layout(G, scale=2, center=(4,5))
self.check_scale_and_center(vpos, scale=2*2, center=(4,5))
vpos = nx.shell_layout(G, scale=2, center=(4,5))
self.check_scale_and_center(vpos, scale=2*2, center=(4,5))
# check default center and scale
vpos = nx.random_layout(G)
self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
vpos = nx.spring_layout(G)
self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
vpos = nx.spectral_layout(G)
self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
vpos = nx.circular_layout(G)
self.check_scale_and_center(vpos, scale=2, center=(0,0))
vpos = nx.shell_layout(G)
self.check_scale_and_center(vpos, scale=2, center=(0,0))
开发者ID:JFriel,项目名称:honours_project,代码行数:26,代码来源:test_layout.py
示例4: getpositions
def getpositions(nodes, links, fixeditem=None):
if nx_available:
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(links)
# print G.number_of_nodes()
# print G.number_of_edges()
# for line in nx.generate_adjlist(G):
# print(line)
if fixeditem:
# so this currently doesnt appear to work
# the node now seems to fix into centre
pos = {1: (0, 0)}
fixlist = [1]
return nx.spring_layout(G, 2, 0.8, pos=pos, fixed=fixlist)
else:
# print nx.spring_layout(G, 2, 1.5, iterations=50)
# TO DO set above to 0,0 for all - object of this is to avoid failure but
# probably will make calling optional shortly
return nx.spring_layout(G, 2, 1.5, iterations=50)
else:
# lets assign 0,0 for now - might move to random
nodedict = {}
for node in nodes:
nodedict[node] = (0, 0)
return nodedict
开发者ID:DonaldMc,项目名称:gdms,代码行数:27,代码来源:netx2py.py
示例5: draw_networkx_ex
def draw_networkx_ex():
G = nx.dodecahedral_graph()
nx.draw(G)
plt.show()
nx.draw_networkx(G, pos=nx.spring_layout(G))
limits = plt.axis('off')
plt.show()
nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
plt.show()
edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
plt.show()
labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
plt.show()
edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
plt.show()
print("Circular layout")
nx.draw_circular(G)
plt.show()
print("Random layout")
nx.draw_random(G)
plt.show()
print("Spectral layout")
nx.draw_spectral(G)
plt.show()
print("Spring layout")
nx.draw_spring(G)
plt.show()
print("Shell layout")
nx.draw_shell(G)
plt.show()
print("Graphviz")
开发者ID:szintakacseva,项目名称:MLTopic,代码行数:31,代码来源:nxdrawing.py
示例6: main
def main():
G_igraph, G_nx, nodes_vector = generate_data()
aca0, aca1 = separate_data_by_academy(nodes_vector, G_nx)
print aca0.nodes()
print aca1.nodes()
plt.subplot(121)
nx.draw_networkx(
G=aca0,
pos=nx.spring_layout(aca0),
with_labels=True,
node_color='g',
edge_color='b',
alpha=1)
plt.axis('off')
plt.subplot(122)
nx.draw_networkx(
G=aca1,
pos=nx.spring_layout(aca1),
with_labels=True,
node_color='g',
edge_color='b',
alpha=1)
plt.axis('off')
plt.show()
开发者ID:NSSimacer,项目名称:SNA,代码行数:31,代码来源:DataProcess.py
示例7: main
def main():
### Undirected graph ###
# Initialize model using the Petersen graph
model=gmm.gmm(nx.petersen_graph())
old_graph=model.get_base()
model.set_termination(node_ceiling)
model.set_rule(rand_add)
# Run simualation with tau=4 and Poisson density for motifs
gmm.algorithms.simulate(model,4)
# View results
new_graph=model.get_base()
print(nx.info(new_graph))
# Draw graphs
old_pos=nx.spring_layout(old_graph)
new_pos=nx.spring_layout(new_graph,iterations=2000)
fig1=plt.figure(figsize=(15,7))
fig1.add_subplot(121)
#fig1.text(0.1,0.9,"Base Graph")
nx.draw(old_graph,pos=old_pos,node_size=25,with_labels=False)
fig1.add_subplot(122)
#fig1.text(0.1,0.45,"Simulation Results")
nx.draw(new_graph,pos=new_pos,node_size=20,with_labels=False)
fig1.savefig("undirected_model.png")
### Directed graph ###
# Initialize model using random directed Barabasi-Albert model
directed_base=nx.barabasi_albert_graph(25,2).to_directed()
directed_model=gmm.gmm(directed_base)
directed_model.set_termination(node_ceiling)
directed_model.set_rule(rand_add)
# Run simualation with tau=4 and Poisson density for motifs
gmm.algorithms.simulate(directed_model,4)
# View results
new_directed=directed_model.get_base()
print(nx.info(new_directed))
# Draw directed graphs
old_dir_pos=new_pos=nx.spring_layout(directed_base)
new_dir_pos=new_pos=nx.spring_layout(new_directed,iterations=2000)
fig2=plt.figure(figsize=(7,10))
fig2.add_subplot(211)
fig2.text(0.1,0.9,"Base Directed Graph")
nx.draw(directed_base,pos=old_dir_pos,node_size=25,with_labels=False)
fig2.add_subplot(212)
fig2.text(0.1,0.45, "Simualtion Results")
nx.draw(new_directed,pos=new_dir_pos,node_size=20,with_labels=False)
fig2.savefig("directed_model.png")
# Export files
nx.write_graphml(model.get_base(), "base_model.graphml")
nx.write_graphml(directed_model.get_base(), "directed_model.graphml")
nx.write_graphml(nx.petersen_graph(), "petersen_graph.graphml")
开发者ID:drewconway,项目名称:GMM,代码行数:60,代码来源:basic_model.py
示例8: drawSprings
def drawSprings(corrMatrix, kclusters, initialPosFileName, mult=1.1):
"""drawSprings draws two figures, one of the spring evolution at 9 timepoints, one of the initial vs. final.
:param corrMatrix: a data object generated by kmeans cluster - has the correlations between objects.
:type corrMatrix: dict - must have 'data' and 'proteins'
:param kclusters: the number of kclusters used in the analysis (what was passed to kmeans)
:type kclusters: int
:param initialPosFileName: a string pointing to the initial positions of each node - see nierhausPositions.txt
:type initialPosFileName: string
:param mult: a float of the base of the exponent to exapand on in each spring interation
:type mult: float
:returns: an array of figures - first is the evolution, second is the start and end.
"""
G = nx.Graph()
positions = readDataFile(initialPosFileName)
initialNodePos = {positions['proteins'][i]: [float(positions['data'][i,0])/4.0, float(positions['data'][i,1])/5.0] for i in range(len(positions['proteins']))}
[G.add_node(x) for x in corrMatrix['proteins']]
connection = (lambda x,y: corrMatrix['data'][x][y])
[G.add_edge(corrMatrix['proteins'][x],corrMatrix['proteins'][y], weight=connection(x,y)) for x in range(len(corrMatrix['proteins'])) for y in range(len(corrMatrix['proteins'])) if (connection(x,y)!=0)]
weights = [G.get_edge_data(x[0],x[1])['weight'] for x in G.edges()]
notes = pylab.figure()
ax = notes.add_subplot(1,2,1, title="nierhaus positions_kclusters=" + str(kclusters))
drawNodePos = initialNodePos
yDiff = [initialNodePos[x][1] - drawNodePos[x][1] for x in drawNodePos.keys()]
nx.draw_networkx(G, pos = drawNodePos,
node_size=600, node_color = yDiff, cmap = pylab.cm.RdBu, vmin=-1, vmax=1,
edge_color=weights, edge_vmin = 0, edge_vmax = kMeansRuns, edge_cmap = pylab.cm.autumn_r, width=2,
font_size=10, font_weight='bold')
iters = int(mult**8)
ax = notes.add_subplot(1,2,2, title="spring iteration=" + str(iters) + "_kclusters=" + str(kclusters))
drawNodePos = nx.spring_layout(G, pos=initialNodePos, iterations=iters)
yDiff = [initialNodePos[x][1] - drawNodePos[x][1] for x in drawNodePos.keys()]
nx.draw_networkx(G, pos = drawNodePos,
node_size=600, node_color = yDiff, cmap = pylab.cm.RdBu, vmin=-1, vmax=1,
edge_color=weights, edge_vmin = 0, edge_vmax = kMeansRuns, edge_cmap = pylab.cm.autumn_r, width=2,
font_size=10, font_weight='bold')
cb1ax = notes.add_axes([0.025, 0.1, 0.05, 0.8])
pylab.colorbar(cmap=pylab.cm.autumn_r, cax=cb1ax)
cb2ax = notes.add_axes([0.925, 0.1, 0.05, 0.8])
norm = mpl.colors.Normalize(vmin=-1, vmax=1)
cb2 = mpl.colorbar.ColorbarBase(cb2ax, cmap=pylab.cm.RdBu_r, norm=norm, orientation='vertical')
notes2 = pylab.figure()
drawNodePos = initialNodePos
for i in range(9):
ax = notes2.add_subplot(3,3,i+1, title="iterations=" + str(int(mult**i)) + "_k=" + str(kclusters))
drawNodePos = nx.spring_layout(G, pos=drawNodePos, iterations=int(mult**i))
yDiff = [initialNodePos[x][1] - drawNodePos[x][1] for x in drawNodePos.keys()]
nx.draw_networkx(G, pos = drawNodePos,
node_size=600, node_color = yDiff, cmap = pylab.cm.RdBu, vmin=-1, vmax=1,
edge_color=weights, edge_vmin = 0, edge_vmax = kMeansRuns, edge_cmap = pylab.cm.autumn_r, width=2,
font_size=10, font_weight='bold')
开发者ID:joeydavis,项目名称:qMSClustering,代码行数:60,代码来源:qMSClustering.py
示例9: test_layouts
def test_layouts():
G =nx.gnm_random_graph(10,15)
rand = [nx.random_layout(G)]
circ = [nx.circular_layout(G)]
#shell = [nx.shell_layout(G)] #same as circular layout...
spectral = [nx.spectral_layout(G)]
tripod = [tripod_layout(G)]
layouts = [rand,circ,spectral, tripod]
regimes = ["random","circular","spectral", "tripod"]
for layout in layouts:
layout.append(nx.spring_layout(G,2,layout[0]))
layout.append(iterate_swaps(G,layout[0]))
layout.append(nx.spring_layout(G,2,layout[2]))
layout.append(greedy_swapper(G,layout[0]))
# Now have list of lists... Find lengths of edgecrossings...
num_crossings = []
for layout in layouts:
for sublayout in layout:
num_crossings.append(count_crosses(G,sublayout))
names = []
for regime in regimes:
names.append(regime)
names.append(regime + "-spring")
names.append(regime + "-swap")
names.append(regime + "-swap-spr")
names.append(regime + "-greedy")
return G, layouts, names, num_crossings
开发者ID:natlund,项目名称:disentangler,代码行数:34,代码来源:disentangler.py
示例10: OnLocalPerturbation
def OnLocalPerturbation(self,e):
k=0
dlg=wx.NumberEntryDialog(self,message='The Number of nodes in cluster, default 3!',prompt='k:',caption='k-anonymity parameter',value=3,min=2,max=40)
if (dlg.ShowModal() == wx.ID_OK):
k=dlg.GetValue()
else:
return
self.rtb.SetValue("")
self.PushStatusText("Starting Local Perturbation", SB_INFO)
self.ShowPos()
if len(self.g.node)!=0:
origin_g=self.g.copy()
result=lp.LocalPerturbation(self.g,k)#perturbation and get the clusters and new graph
self.g=result[1]
OutStr="the clusters:\n"
for c in result[0]:
OutStr=OutStr+str(tuple(c))+"\n"
self.rtb.SetValue(OutStr)
plt.figure("comparison")
plt.subplot(211)
plt.title ("original graph")
nx.draw(origin_g,with_labels=True,pos=nx.spring_layout(origin_g))
plt.subplot(212)
plt.title("new graph")
nx.draw(self.g,with_labels=True,pos=nx.spring_layout(self.g))
plt.show()
else:
print 'Grap is empty!! Please load data!'
wx.MessageBox("No data was selected. Please load data!","Data Error")
开发者ID:liupenggl,项目名称:dpr,代码行数:29,代码来源:DataPrivacy.py
示例11: Asymmetric_Networks
def Asymmetric_Networks():
G_asymmetric = nx.DiGraph()
G_asymmetric.add_edge('A', 'B')
G_asymmetric.add_edge('A', 'D')
G_asymmetric.add_edge('C', 'A')
G_asymmetric.add_edge('D', 'E')
nx.spring_layout(G_asymmetric)
nx.draw_networkx(G_asymmetric)
开发者ID:1v1expert,项目名称:UniversityTasks,代码行数:8,代码来源:main.py
示例12: add_ndex_spring_layout_with_attractors
def add_ndex_spring_layout_with_attractors(g, node_width, attractor_map, iterations=None, use_degree_edge_weights=False):
fixed = []
initial_pos = {}
g_simple = _create_simple_graph(g)
next_node_id = max(g_simple.nodes()) + 1
cc = sorted(nx.connected_components(g_simple), key = len, reverse=True)
if len(cc) > 1:
print("%s disconnected subgraphs: adding centerpoint attractor with edges to one of the least connected nodes in each subgraph" % len(cc))
anchor_node_ids = []
for c in cc:
cl = list(c)
min_degree = min(cl)
min_index = cl.index(min_degree)
node_id = cl[min_index]
anchor_node_ids.append(node_id)
attractor_id = next_node_id
g_simple.add_node(next_node_id)
next_node_id = next_node_id + 1
fixed.append(attractor_id)
initial_pos[attractor_id] = (0.5, 0.5)
for node_id in anchor_node_ids:
g_simple.add_edge(node_id, attractor_id)
for attractor in attractor_map:
attractor_id = next_node_id
g_simple.add_node(next_node_id)
next_node_id = next_node_id + 1
fixed.append(attractor_id)
initial_pos[attractor_id] = attractor["position"]
for node_id in attractor["node_ids"]:
g_simple.add_edge(node_id, attractor_id) # , {"weight":2.5})
if use_degree_edge_weights:
_add_degree_edge_weights(g_simple)
scaled_pos = {}
scale_factor = 4 * node_width * math.sqrt(g.number_of_nodes())
for node in g_simple.nodes():
x_pos = random.random() * scale_factor
y_pos = random.random() * scale_factor
scaled_pos[node] = (x_pos, y_pos)
for node_id in initial_pos:
position = initial_pos[node_id]
scaled_pos[node_id] = (scale_factor * position[0], scale_factor * position[1])
if len(fixed) > 0:
final_positions = nx.spring_layout(g_simple, fixed=fixed, pos=scaled_pos, iterations=iterations)
for node_id in fixed:
final_positions.pop(node_id)
else:
final_positions = nx.spring_layout(g_simple, pos=scaled_pos, iterations=iterations)
g.pos = final_positions
开发者ID:ndexbio,项目名称:ndex-python,代码行数:58,代码来源:layouts.py
示例13: test_algo_euler4
def test_algo_euler4(self):
fLOG (__file__, self._testMethodName, OutputPrint = __name__ == "__main__")
folder = os.path.join(os.path.abspath(os.path.dirname(__file__)),"temp_rues5")
if not os.path.exists(folder) : os.mkdir(folder)
edges = get_data(whereTo=folder)
edges = edges[:3]
vertices = { }
for e in edges :
for i in range(0,2):
_ = e[i]
p = e[i+3]
vertices[_] = p
connex = connected_components(edges)
v = [ v for k,v in connex.items() ]
mi,ma = min(v), max(v)
while mi != ma :
edges.append( (mi, ma, 2, vertices[mi], vertices[ma],
distance_haversine( * (vertices[mi] + vertices[ma]) ) ) )
connex = connected_components(edges)
v = [ v for k,v in connex.items() ]
mi,ma = min(v), max(v)
if __name__ == "__main__":
import matplotlib.pyplot as plt
import networkx as nx
fig = plt.figure()
G = nx.Graph()
for e in edges :
a,b = e[:2]
G.add_edge(a,b)
pos = nx.spring_layout(G)
nx.draw(G,pos,node_color='#A0CBE2')
plt.savefig(os.path.join(folder, "graph1.png"))
added = eulerien_extension( edges, fLOG=lambda *l : None,
distance = distance_paris)
if __name__ == "__main__":
for e in added :
a,b = e[:2]
G.add_edge(a,b)
fig = plt.figure()
pos = nx.spring_layout(G)
deg = graph_degree(edges + added)
#labels={ v:"{0}".format(deg[v]) for v in G.nodes() }
nx.draw(G,pos,node_color='#A0CBE2'#,labels=labels
)
plt.savefig(os.path.join(folder, "graph2.png"))
path = euler_path(edges, added)
all = edges + added
fLOG(len(all),len(path))
开发者ID:athabault,项目名称:ensae_teaching_cs,代码行数:56,代码来源:test_rue_paris.py
示例14: display
def display(Y):
weight = 0.03
node_size = 50
node_alpha = 0.5
node_color = "blue"
edge_tickness = 0.5
edge_alpha = 0.5
edge_color = "black"
scores = get_histogram(Y)
F = plt.figure()
ax1 = F.add_subplot(2,2,1)
ax1.hist(scores,bins=30, color="green", edgecolor="white")
ax1.set_xlabel("Pearons Correlation Coefficient")
ax1.set_ylabel("Frequency")
ax2 = F.add_subplot(2,2,2)
G = make_network(Y,threshold=0.95,weight=weight)
pos = nx.spring_layout(G)
nx.draw(G, pos,ax=ax2,node_size=15)
nx.draw_networkx_nodes(G,pos,node_size=node_size,
alpha=node_alpha, node_color=node_color)
nx.draw_networkx_edges(G,pos,width=edge_tickness,
alpha=edge_alpha,edge_color=edge_color)
ax2.set_title("Network Thresholded, > 0.95")
ax3 = F.add_subplot(2,2,3)
ax3.set_title("Network Thresholded, > 0.55")
G = make_network(Y,threshold=0.55,weight=weight)
pos = nx.spring_layout(G)
nx.draw(G, pos,ax=ax3,node_size=15)
nx.draw_networkx_nodes(G,pos,node_size=node_size,
alpha=node_alpha, node_color=node_color)
nx.draw_networkx_edges(G,pos,width=edge_tickness,
alpha=edge_alpha,edge_color=edge_color)
ax4 = F.add_subplot(2,2,4)
penalties = np.linspace(0.0, 1.0,20)
counts = [len([x for x in nx.connected_components(make_network(Y,threshold=p, weight=1,add=True))]) for p in penalties]
ax4.plot(penalties, counts)
ax4.scatter(penalties, counts)
ax4.set_xlabel("Pearon's Treshold")
ax4.set_ylabel("Number of Connected Components")
plt.tight_layout()
plt.show()
开发者ID:azofeifa,项目名称:Correlation_Analysis,代码行数:55,代码来源:compute_correlations.py
示例15: create_plot1
def create_plot1(g, df=None, dedirect=False, flatten=False, edgelabels = True,
nodelabels=True, fsize=None, K=None, save=False):
"""Creates a graph from a figure
returns/shows a figure.
Args:
g - (networkx graph object)
df - pandas dataframe object. Default is None
dedirect - converts networkx DiGraph to Graph. Default is False
flatten - manipultes a graph by replacing nodes that have only two
edges with straighforward edge. Also, groups these kind of edges if
it is possible
edgelabels . Default is None
nodelables . Default is None
fsize
K
Save
Returns:
matplotlib figure
"""
if dedirect==True:
g = nx.Graph(g)
if fsize != None:
plt.figure(1, figsize=fsize)
pos = nx.spring_layout(g, dim=2, scale=1)
if flatten == True:
g = flatten_graph(g)
pos = nx.spring_layout(g, dim=2, scale=1)
pos = nx.spring_layout(g, dim=2, scale=10, k=K)
node_colors = get_node_colors(g.nodes(), df)
nx.draw_networkx_nodes(g, pos, alpha=0.3, node_size=300, node_color=node_colors)
edge_colors = get_edge_colors(g.edges(), df)
nx.draw_networkx_edges(g, pos, alpha=0.1, edge_color='b')
if nodelabels == True:
nx.draw_networkx_labels(g, pos)
if edgelabels == True:
nx.draw_networkx_edge_labels(g, pos)
if save == True:
mpld3.save_html(figure(1), 'graph.html')
return plt.figure(1)
开发者ID:aidiss,项目名称:Lithuanian-Academic-Circles-and-Their-Networks,代码行数:55,代码来源:create_plot.py
示例16: test_plot
def test_plot(image):
graph = nx.from_numpy_matrix(image)
plt.subplot2grid((9, 3), (0, 0), rowspan=3, colspan=3)
nx.draw(graph, nx.spring_layout(graph))
plt.hold(True)
plt.subplot2grid((9, 3), (3, 0), rowspan=3, colspan=3)
nx.draw(graph, nx.spring_layout(graph))
plt.hold(True)
plt.subplot2grid((9, 3), (6, 0), rowspan=3, colspan=3)
nx.draw(graph, nx.spring_layout(graph))
plt.axis('tight')
plt.show()
开发者ID:kirk86,项目名称:Task-1,代码行数:12,代码来源:plots.py
示例17: autoCoordinates
def autoCoordinates(meshEntry,srcdesConnection):
#for cmpt,memb in meshEntry.items():
# print memb
xmin = 0.0
xmax = 1.0
ymin = 0.0
ymax = 1.0
G = nx.Graph()
for cmpt,memb in meshEntry.items():
for enzObj in find_index(memb,'enzyme'):
G.add_node(enzObj.path)
for cmpt,memb in meshEntry.items():
for poolObj in find_index(memb,'pool'):
G.add_node(poolObj.path)
for cplxObj in find_index(memb,'cplx'):
G.add_node(cplxObj.path)
G.add_edge((cplxObj.parent).path,cplxObj.path)
for reaObj in find_index(memb,'reaction'):
G.add_node(reaObj.path)
for inn,out in srcdesConnection.items():
if (inn.className =='ZombieReac'): arrowcolor = 'green'
elif(inn.className =='ZombieEnz'): arrowcolor = 'red'
else: arrowcolor = 'blue'
if isinstance(out,tuple):
if len(out[0])== 0:
print inn.className + ':' +inn[0].name + " doesn't have input message"
else:
for items in (items for items in out[0] ):
G.add_edge(element(items[0]).path,inn.path)
if len(out[1]) == 0:
print inn.className + ':' + inn[0].name + "doesn't have output mssg"
else:
for items in (items for items in out[1] ):
G.add_edge(inn.path,element(items[0]).path)
elif isinstance(out,list):
if len(out) == 0:
print "Func pool doesn't have sumtotal"
else:
for items in (items for items in out ):
G.add_edge(element(items[0]).path,inn.path)
nx.draw(G,pos=nx.spring_layout(G))
#plt.savefig('/home/harsha/Desktop/netwrokXtest.png')
xcord = []
ycord = []
position = nx.spring_layout(G)
for y in position.values():
xcord.append(y[0])
ycord.append(y[1])
return(min(xcord),max(xcord),min(ycord),max(ycord),position)
开发者ID:saeedsh,项目名称:async_gpu,代码行数:52,代码来源:kkitOrdinateUtil.py
示例18: plot_graph
def plot_graph(graph, fixed=None, positions=None, show_plot=True, fpath=None):
"""Plot graph.
Parameters
----------
graph : networkx.MultiDiGraph
Output from `make_graph`
fixed : {None}, list, optional
Node around which to fix graph. Overrides `positions`.
Example: fixed=['mod1']
positions : {None}, dict, optional
``dict`` of ``list`` output from `make_positions_dict`.
Requires `fixed` is ``None``, otherwise overridden.
show_plot : {True, False}, bool, optional
Flag to display plot in window.
fpath : {None}, string, optional
Path for plotting graph.
Returns
-------
None
See Also
--------
CALLS : {}
CALLED_BY : {}
RELATED : {make_positions_dict, make_graph}
"""
# TODO: Space out points. Scale to larger image?
# TODO: make relationships different colors
# Check input and define positions.
if fixed is None:
if positions is None:
pos = nx.spring_layout(graph, fixed=fixed)
else:
pos = positions
else:
if positions is not None:
warnings.warn(
("\n" +
"`fixed` overrides `positions`:\n" +
"fixed = {fixed}").format(
fixed=fixed))
pos = nx.spring_layout(graph, fixed=fixed)
# Draw graph and save.
nx.draw(graph, pos=pos)
nx.draw_networkx_labels(graph, pos=pos)
if fpath is not None:
plt.savefig(fpath, bbox_inches='tight')
plt.show()
return None
开发者ID:stharrold,项目名称:doc,代码行数:52,代码来源:utils.py
示例19: main
def main(G):
"""draw the input graph and the colored out put graph
determine the centroides and clusters
"""
try:
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_colors = 'k'
edge_labels=dict([((u,v,),d['weight'])
for u,v,d in G.edges(data=True)])
pos=nx.spring_layout(G) # positions for all nodes
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=15,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()
km = BKM.KMeans(G, n_clusters, max_iter=100)
pos=nx.spring_layout(G) # positions for all nodes
node_colors = ['b','g','r','y','c','k','m']
for i in range(len(G)):
node_colors.append('w')
# nodes
Clust = km.fit_predict(G)[1]
for item in range(n_clusters):
for group in Clust[item]:
nx.draw_networkx_nodes(G,pos,
nodelist = Clust[item],
node_color=node_colors[item],
node_size=80,
alpha=0.8)
edge_colors = 'k'
edge_labels=dict([((u,v,),d['weight'])
for u,v,d in G.edges(data=True)])
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=1,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()
print(km.__str__())
except BKM.KMeansError:
print( "Got an imput error, please change the input and try it again." )
开发者ID:liuqingjie,项目名称:Network-Clustering,代码行数:51,代码来源:test.py
示例20: main
def main(G):
"""draw the input graph and the colored out put graph
determine the clusters after each level of merging
"""
try:
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_colors = 'k'
edge_labels=dict([((u,v,),d['weight'])
for u,v,d in G.edges(data=True)])
pos=nx.spring_layout(G) # positions for all nodes
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=15,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()
for ite in range(len(G.nodes())):
Iterations = ite
AL = AVG.Average_linkage(G, Iterations)
#print(AL.__str__())
pos=nx.spring_layout(G) # positions for all nodes
node_colors = ['b','g','r','y','c','k','m']
for i in range(len(G)):
node_colors.append('w')
# nodes
C_list = AL.fit_predict(G)[-1,:]
for Clust in range(C_list.shape[1]):
nx.draw_networkx_nodes(G,pos,
nodelist = list(C_list[0,Clust]),
node_color=node_colors[Clust],
node_size=80,
alpha=0.8)
# edges
nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
plt.axis('off')
plt.savefig("labels_and_colors.png") # save as png
plt.show() # display
print "in level :",ite
print AL.__str__()
except AVG.Average_linkage_Error:
print( "Got an imput error, please change the input and try it again." )
开发者ID:NunoEdgarGub1,项目名称:Network-Clustering,代码行数:51,代码来源:test.py
注:本文中的networkx.spring_layout函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论