## Írányítatlan gráf
### Alap importálás
import networkx as nx
import json
import matplotlib.pyplot as plt
%matplotlib inline
G = nx.erdos_renyi_graph(30,4.0/30)
while not nx.is_connected(G):
G = nx.erdos_renyi_graph(30,4.0/30) ## Minta
# Megjelenítés
plt.figure(figsize=(10,6));
nx.draw(G, font_size=14, with_labels=True)
## JSON-ba mentés
from networkx.readwrite import json_graph
data = json_graph.node_link_data(G)
with open('graph.json', 'w') as f:
json.dump(data, f, indent=4)
import networkx as nx
import json
import matplotlib.pyplot as plt
%matplotlib inline
sql='''---- ODI LP MAP függőség megjelenítése
select 'g.add_edge('|| t.FROM_STEP_ID ||', '|| t.TO_STEP_ID || ')'
--t.FROM_STEP_ID, t.TO_STEP_ID, step.LOAD_PLAN_ID
from odi_repo.lp_step_transitions t , odi_repo.lp_steps step
where step.id = t.TO_STEP_ID and step.LOAD_PLAN_ID = 806826 ---TOLTES-ID
'''
g = nx.DiGraph() ## empty graph / Üres gráf
## feltöltés
g.add_edge(806827, 806859)
g.add_edge(806829, 806860)
g.add_edge(806830, 806860)
g.add_edge(806831, 806860)
g.add_edge(806832, 806860)
g.add_edge(806833, 806860)
g.add_edge(806834, 806860)
g.add_edge(806835, 806860)
g.add_edge(806836, 806860)
g.add_edge(806837, 806860)
g.add_edge(806838, 806860)
g.add_edge(806839, 806861)
g.add_edge(806840, 806860)
g.add_edge(806841, 806828)
g.add_edge(806842, 806860)
g.add_edge(806843, 806860)
g.add_edge(806844, 806860)
g.add_edge(806845, 806860)
g.add_edge(806846, 806860)
g.add_edge(806847, 806861)
g.add_edge(806848, 806860)
g.add_edge(806849, 806860)
g.add_edge(806850, 806860)
g.add_edge(806851, 806860)
g.add_edge(806852, 806860)
g.add_edge(806853, 806860)
g.add_edge(806854, 806860)
g.add_edge(806855, 806860)
g.add_edge(806856, 806860)
g.add_edge(806857, 806860)
g.add_edge(806858, 806854)
g.add_edge(806859, 806862)
g.add_edge(806860, 806841)
g.add_edge(806861, 806851)
g.add_edge(806862, 806829)
g.add_edge(806862, 806830)
g.add_edge(806862, 806831)
g.add_edge(806862, 806832)
g.add_edge(806862, 806833)
g.add_edge(806862, 806834)
g.add_edge(806862, 806835)
g.add_edge(806862, 806836)
g.add_edge(806862, 806837)
g.add_edge(806862, 806838)
g.add_edge(806862, 806839)
g.add_edge(806862, 806840)
g.add_edge(806862, 806842)
g.add_edge(806862, 806843)
g.add_edge(806862, 806844)
g.add_edge(806862, 806845)
g.add_edge(806862, 806846)
g.add_edge(806862, 806847)
g.add_edge(806862, 806848)
g.add_edge(806862, 806849)
g.add_edge(806862, 806850)
g.add_edge(806862, 806852)
g.add_edge(806862, 806853)
g.add_edge(806862, 806855)
g.add_edge(806862, 806856, color="green")
g.add_edge(806862, 806857, color="green")
pos = nx.circular_layout(g) ## körgyűrűbe rendezés
plt.figure(figsize=(10,6)); ## Szélesség / magasság
nx.draw(g, pos, font_size=14, node_color='green', edge_color='blue', with_labels=True)
## számolások
N, K = g.order(), g.size()
avg_deg= float(K) / N
print ("Csúcsok: ", N)
print ("Élek: ", K)
print ("Átlag: ", avg_deg)
## hurok vizsgálat
print ('Hurok : ', list(nx.simple_cycles(g)))
## legrővidebb út megjelenítése
print('Legrövideb út2: ',nx.dijkstra_path(g, source = 806862, target = 806860))
print('Legrövideb út1: ',nx.shortest_path(g, source = 806862, target = 806860))
Csúcsok: 36 Élek: 60 Átlag: 1.6666666666666667 Hurok : [] Legrövideb út2: [806862, 806829, 806860] Legrövideb út1: [806862, 806829, 806860]
import networkx as nx
import json
import matplotlib.pyplot as plt
%matplotlib inline
G = nx.Graph()
G.add_edge(1,2, color='r', weight=2)
G.add_edge(2,3, color='b', weight=4)
G.add_edge(3,4, color='g', weight=6)
G.add_edge(3,5, color='y', weight=6)
pos = nx.circular_layout(G)
edges = G.edges()
colors = [G[u][v]['color'] for u,v in edges]
weights = [G[u][v]['weight'] for u,v in edges]
nx.draw(G, pos, edges=edges, edge_color=colors, node_color='lightgreen', width=weights, with_labels=True)
import networkx as nx
import json
import matplotlib.pyplot as plt
%matplotlib inline
G = nx.Graph()
G.add_edge(0,1,color='r',weight=2)
G.add_edge(1,2,color='g',weight=4)
G.add_edge(2,3,color='b',weight=6)
G.add_edge(3,4,color='y',weight=3)
G.add_edge(4,0,color='m',weight=5)
colors = nx.get_edge_attributes(G,'color').values()
weights = nx.get_edge_attributes(G,'weight').values()
pos = nx.circular_layout(G)
nx.draw(G, pos,
edge_color=colors,
width=list(weights),
with_labels=True,
node_color='lightgreen')
import networkx as nx
import json
import matplotlib.pyplot as plt
%matplotlib inline
G1=nx.DiGraph()
G1.add_edge(1, 2, weight = 2.0)
G1.add_edge(1,3)
G1.add_edge(2, 3, weight = 1.0)
G1.add_edge(2, 4, weight = 4.0)
G1.add_edge(2, 5, weight = 2.0)
G1.add_edge(3, 5)
G1.add_edge(4, 6, weight = 2.0)
G1.add_edge(5, 4, weight = 3.0)
G1.add_edge(5, 6, weight = 2.0)
G1.edges()
G1.nodes[1]['pos'] = (0,0)
G1.nodes[2]['pos'] = (2,2)
G1.nodes[3]['pos'] = (2,-2)
G1.nodes[4]['pos'] = (5,2)
G1.nodes[5]['pos'] = (5,-2)
G1.nodes[6]['pos'] = (7,0)
node_pos=nx.get_node_attributes(G1,'pos')
arc_weight=nx.get_edge_attributes(G1,'weight')
nx.draw_networkx(G1, node_pos, node_size=450)
nx.draw_networkx_edges(G1, node_pos, edge_color='green')
# Draw the edge labels
nx.draw_networkx_edge_labels(G1, node_pos, edge_labels=arc_weight)
# Remove the axis
plt.axis('off')
# Show the plot
plt.show()
def read_json_file(filename):
with open(filename) as f:
js_graph = json.load(f)
return nx.json_graph.node_link_graph(js_graph)
G = read_json_file(r"graph.json")
plt.figure(figsize=(10,6)); ## Szélesség / magasság
nx.draw(G, font_size=14, with_labels=True)
import networkx as nx
from networkx.readwrite import json_graph
import json
G = nx.Graph([('A', 'B')])
data1 = json_graph.node_link_data(G)
H = nx.gn_graph(2)
data2 = json_graph.node_link_data(H, {'link': 'edges', 'source': 'from', 'target': 'to'})
s1 = json.dumps(data1)
s2 = json.dumps(data2, default={'link': 'edges', 'source': 'from', 'target': 'to'})
import networkx as nx
g = nx.Graph() # empty graph / Üres gráf
g.add_edge('a', 'b', weight=0.1)
g.add_edge('b', 'c', weight=1.5)
g.add_edge('a', 'c', weight=1.0)
g.add_edge('c', 'd', weight=2.2)
print (nx.shortest_path(g, 'b', 'd')) ##-> ['b', 'c', 'd']
print (nx.shortest_path(g, 'b', 'd', weight='weight')) ## -> ['b', 'a', 'c', 'd']
['b', 'c', 'd'] ['b', 'a', 'c', 'd']
# One node at a time
g.add_node(1)
# A list of nodes
g.add_nodes_from([2, 3])
# A container of nodes
h = nx.path_graph(5)
g.add_nodes_from(h)
# You can also remove any node of the graph
g.remove_node(2)
# Single edge
g.add_edge(1, 2)
e = (2, 3)
g.add_edge(*e) # unpack tuple
# List of edges
g.add_edges_from([(1, 2), (1, 3)])
# A container of edges
g.add_edges_from(h.edges())
# You can also remove any edge
g.remove_edge(1, 2)
g.add_edges_from([(1, 2), (1, 3)])
g.add_node('a')
g.number_of_nodes() # also g.order()
g.number_of_edges() # also g.size()
g.nodes() ## -> ['a', 1, 2, 3]
g.edges() ## -> [(1, 2), (1, 3)]
plt.figure(figsize=(10,6));
nx.draw(g, font_size=14, with_labels=True, edge_color='red')
dg = nx.DiGraph() ## irányított gráf
dg.add_weighted_edges_from([(1, 4, 0.5), (3, 1, 0.75)])
dg.out_degree(1, weight='weight') ##-> 0.5
dg.degree(1, weight='weight') ##-> 1.25
dg.successors(1) ##-> [4]
dg.predecessors(1) ## ->
plt.figure(figsize=(10,6));
nx.draw(dg, font_size=14, edge_color='green', with_labels=True)
kl_help = '''
Graf -ok közötti műveletek
• subgraph(G, nbunch) - induce subgraph of G on nodes in nbunch
• union(G1, G2) - graph union, G1 and G2 must be disjoint
• cartesian_product(G1, G2) - return Cartesian product graph
• compose(G1, G2) - combine graphs identifying nodes common to both
• complement(G) - graph complement
• create_empty_copy(G) - return an empty copy of the same graph class
• convert_to_undirected(G) - return an undirected representation of G
• convert_to_directed(G) - return a directed representation of G
---
# small famous graphs
>>> petersen = nx.petersen_graph()
>>> tutte = nx.tutte_graph()
>>> maze = nx.sedgewick_maze_graph()
>>> tet = nx.tetrahedral_graph()
---
# classic graphs
>>> K_5 = nx.complete_graph(5)
>>> K_3_5 = nx.complete_bipartite_graph(3, 5)
>>> barbell = nx.barbell_graph(10, 10)
>>> lollipop = nx.lollipop_graph(10, 20)
---
# random graphs
>>> er = nx.erdos_renyi_graph(100, 0.15)
>>> ws = nx.watts_strogatz_graph(30, 3, 0.1)
>>> ba = nx.barabasi_albert_graph(100, 5)
>>> red = nx.random_lobster(100, 0.9, 0.9)
•General read/write
•Read and write edge lists
•Data formats
•Node pairs with no data: 1 2
•Python dictionaries as data: 1 2 {'weight':7, 'color':'green'}
•Arbitrary data: 1 2 7 green
---
g = nx.read_<format>(‘path/to/file.txt’,...options...)
nx.write_<format>(g,‘path/to/file.txt’,...options...)
g = nx.read_edgelist(path, comments='#', create_using=None, delimiter=' ', nodetype=None, data=True, edgetype=None, encoding='utf-8')
nx.write_edgelist(g, path,
'''
import matplotlib.pyplot as plt
import networkx as nx
G = nx.cubical_graph() ## kocka alap gráf
pos = nx.spring_layout(G) # positions for all nodes
#print(pos)
# nodes
options = {"node_size": 500, "alpha": 0.8}
nx.draw_networkx_nodes(G, pos, nodelist=[0, 1, 2, 3], node_color="r", **options)
nx.draw_networkx_nodes(G, pos, nodelist=[4, 5, 6, 7], node_color="b", **options)
# edges
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
nx.draw_networkx_edges(
G,
pos,
edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
width=8,
alpha=0.5,
edge_color="r",
)
nx.draw_networkx_edges(
G,
pos,
edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
width=8,
alpha=0.5,
edge_color="b",
)
nx.draw_networkx_edges(
G,
pos,
edgelist=[(0, 4),(2, 6), (1,7), (3,5)],
width=8,
alpha=0.5,
edge_color="g",
)
# some math labels
labels = {}
labels[0] = r"$a$"
labels[1] = r"$b$"
labels[2] = r"$c$"
labels[3] = r"$d$"
labels[4] = r"$\alpha$"
labels[5] = r"$\beta$"
labels[6] = r"$\gamma$"
labels[7] = r"$\delta$"
nx.draw_networkx_labels(G, pos, labels, font_size=16) ## node cimke/label
plt.axis("off") ## keret kikapcsolása
plt.figure(figsize=(10,6));
plt.show() ## megjelenítés
<Figure size 720x432 with 0 Axes>
import matplotlib.pyplot as plt
import networkx as nx
G = nx.path_graph(8)
nx.draw(G, font_size=14, with_labels=True)
plt.figure(figsize=(10,6));
plt.show()
<Figure size 720x432 with 0 Axes>
cam_net=nx.lollipop_graph(10, 20)
N, K = cam_net.order(), cam_net.size()
avg_deg= float(K) / N
print ("Nodes: ", N)
print ("Edges: ", K)
print ("Average degree: ", avg_deg)
nx.draw(cam_net, font_size=14, with_labels=True)
plt.show()
Nodes: 30 Edges: 65 Average degree: 2.1666666666666665
## Irányítatlan
g = nx.Graph() #empty graph
g.add_node(1)
g.add_nodes_from([2, 3])
# A container of nodes
h = nx.path_graph(5)
g.add_nodes_from(h)
# You can also remove any node of the graph
g.remove_node(2)
g.add_edges_from([(1, 2), (1, 3)])
print(g.number_of_nodes())
print(g.number_of_edges())
for node in g.nodes(): # or node
print (node , g.degree(node))
nx.draw(g, font_size=14, edge_color='blue', with_labels=True)
plt.show()
5 2 1 2 3 1 0 0 4 0 2 1
import networkx as nx
from networkx.readwrite import json_graph
## irányított Gráf és hurok keresés
dg = nx.DiGraph()
dg.add_weighted_edges_from([(1, 4, 0.5), (3, 1, 0.75)])
dg.add_weighted_edges_from([(4, 3, 0.5), (4, 5, 0.75)])
print(dg.out_degree(1, weight='weight')) ## -> 0.5
print(dg.degree(1, weight='weight')) ##-> 1.25
print(dg.successors(1)) ##-> [4]
print(dg.predecessors(1)) ##-> [3]
N, K = dg.order(), dg.size()
avg_deg= float(K) / N
print ("Nodes: ", N)
print ("Edges: ", K)
print ("Average degree: ", avg_deg)
print ("SCC: ", nx.number_strongly_connected_components(dg))
print("WCC: ", nx.number_weakly_connected_components(dg))
print('Hurok : ',list(nx.simple_cycles(dg)))
nx.draw(dg,font_size=14, edge_color='red', with_labels=True)
nx.write_gml(dg, "gml_file.gml") ## Kiírás
#mygraph = nx.read_gml("gml_file.gml") ## beOlvasás
plt.show()
0.5 1.25 <dict_keyiterator object at 0x0000020AEA051868> <dict_keyiterator object at 0x0000020AEA051868> Nodes: 4 Edges: 4 Average degree: 1.0 SCC: 2 WCC: 1 Hurok : [[1, 4, 3]]
import pylab as plt ##import Matplotlib plotting interface
g = nx.watts_strogatz_graph(30, 8, 0.1)
nx.draw(g, font_size=14, with_labels=True)
#nx.draw_random(g, font_size=14, with_labels=True) ## véletlenszerű
#nx.draw_circular(g, font_size=16, with_labels=True) ## körkörösen
#nx.draw_spectral(g, font_size=12, with_labels=True) ## spektumszerint
print('Order : ', G.order())
print('Size : ', G.size())
plt.savefig('graph.png')
Order : 29 Size : 163
#! /usr/bin/env python3
import networkx as nx
from networkx.readwrite import json_graph
##import json, community
from networkx.algorithms import centrality as cn
# Nodes and edges csv files are in Gephi form. Get information into usable dictionaries and tuples.
# Creates dictionary of id:name pairs.
with open(r'c:\Users\Downloads\marvel_nodes.csv') as nodecsv:
rows = nodecsv.read().split('\n')
# print(rows)
node_dict = {}
for r in rows[1:30]: ## első 30 db beolvasása
r = r.split(',')
node_dict[r[0]] = r[1]
# print(node_dict)
node_dict={k:v.title() for k,v in node_dict.items()}
node_ids = node_dict.keys()
nodes = node_dict.values()
# Creates tuples with source, target, and weight.
with open(r'c:\Users\Downloads\marvel_edges.csv') as edgecsv:
rows = edgecsv.read().split('\n')
edges = [r.split(',')[:2] for r in rows[1:]]
weights = [r.split(',')[-1] for r in rows[1:]]
edge_tuples=[(e[0], e[1], int(weights[i])) for i,e in enumerate(edges)]
# Only get edges for the select nodes in the node csv.
edges = []
for e in edge_tuples:
if all(x in list(node_ids) for x in e[:2]):
edges.append(e)
# Initialize graph, add nodes and edges, calculate modularity and centrality.
G = nx.Graph()
G.add_nodes_from(list(node_ids))
G.add_weighted_edges_from(edges)
nx.draw(G, font_size=14, edge_color='red', with_labels=True)
plt.show()
kl_help='''
groups = community.best_partition(G)
degree = cn.degree_centrality(G)
betweenness = cn.betweenness_centrality(G, weight='weight')
eigenvector = cn.eigenvector_centrality(G, weight='weight')
# Add node attributes for name, modularity, and three types of centrality.
nx.set_node_attributes(G, 'name', node_dict)
nx.set_node_attributes(G, 'group', groups)
nx.set_node_attributes(G, 'degree', degree)
nx.set_node_attributes(G, 'betweenness', betweenness)
nx.set_node_attributes(G, 'eigenvector', eigenvector)
# Create json representation of the graph (for d3).
data = json_graph.node_link_data(G)
# You could create the needed json without NetworkX (but you would forfeit network metrics).
#new_data = dict(nodes=[dict(id=n) for n in list(set(nodes))], links=[dict(source=node_dict[e[0]], target=node_dict[e[1]], weight=e[2]) for e in edges])
# Output json of the graph.
with open('marvel.json', 'w') as output:
json.dump(data, output, sort_keys=True, indent=4, separators=(',',':'))
'''
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-39-e35881b8467f> in <module> 8 9 # Creates dictionary of id:name pairs. ---> 10 with open(r'c:\Users\Downloads\marvel_nodes.csv') as nodecsv: 11 rows = nodecsv.read().split('\n') 12 # print(rows) FileNotFoundError: [Errno 2] No such file or directory: 'c:\\Users\\Downloads\\marvel_nodes.csv'
import matplotlib.pyplot as plt
import networkx as nx
G=nx.grid_2d_graph(4,4) #4x4 grid
pos=nx.spring_layout(G,iterations=100)
plt.subplot(221)
nx.draw(G,pos,font_size=8, with_labels=True)
plt.subplot(222)
nx.draw(G,pos,node_color='k',node_size=0,with_labels=False)
plt.subplot(223)
nx.draw(G,pos,node_color='g',node_size=250,with_labels=False,width=6)
plt.subplot(224)
H=G.to_directed()
nx.draw(H,pos,node_color='b',node_size=20,with_labels=False)
plt.savefig("four_grids.png")
plt.show()
import networkx as nx
G=nx.star_graph(20)
pos=nx.spring_layout(G)
colors=range(20)
nx.draw(G,pos, node_color='#A0CBE2',edge_color=colors, width=4, edge_cmap=plt.cm.Blues,with_labels=True)
plt.savefig("edge_colormap.png") # save as png
plt.show() # display
import networkx as nx
import matplotlib.pyplot as plt
G = nx.gnp_random_graph(100,0.02)
## degree_sequence=sorted(nx.degree(G).values(),reverse=True) # degree sequence //hibát ad
#degree_sequence=sorted([v for k, v in nx.degree(G)],reverse=True) # degree sequence jó 1
degree_sequence=sorted(dict(nx.degree(G)).values(),reverse=True) # degree sequence jó 2
#print "Degree sequence", degree_sequence
dmax=max(degree_sequence)
plt.loglog(degree_sequence,'b-',marker='o')
plt.title("Degree rank plot")
plt.ylabel("degree")
plt.xlabel("rank")
# draw graph in inset
plt.axes([0.45,0.45,0.45,0.45])
Gcc=sorted(nx.connected_component_subgraphs(G), key = len, reverse=True)[0]
pos=nx.spring_layout(Gcc)
plt.axis('off')
nx.draw_networkx_nodes(Gcc,pos,node_size=20)
nx.draw_networkx_edges(Gcc,pos,alpha=0.4)
plt.savefig("degree_histogram.png")
plt.show()
import networkx as nx
G=nx.cycle_graph(24)
pos=nx.spring_layout(G,iterations=200)
nx.draw(G,pos,node_color=range(24),node_size=800,cmap=plt.cm.Blues, with_labels=True)
plt.savefig("node_colormap.png") # save as png
plt.show() # display
import networkx as nx
import matplotlib.pyplot as plt
G=nx.random_geometric_graph(200,0.125)
# position is stored as node attribute data for random_geometric_graph
pos=nx.get_node_attributes(G,'pos')
# find node near center (0.5,0.5)
dmin=1
ncenter=0
for n in pos:
x,y=pos[n]
d=(x-0.5)**2+(y-0.5)**2
if d<dmin:
ncenter=n
dmin=d
# color by path length from node near center font_size=14, edge_color='red', with_labels=True)
p=nx.single_source_shortest_path_length(G,ncenter)
plt.figure(figsize=(8,8))
nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4)
nx.draw_networkx_nodes(G,pos,nodelist=p.keys(),
node_size=180,
node_color=list(p.values()), font_size=14, with_labels=True,
cmap=plt.cm.Reds_r) ##
plt.xlim(-0.05,1.05)
plt.ylim(-0.05,1.05)
plt.axis('off')
plt.savefig('random_geometric_graph.png')
plt.show()
import networkx as nx
G=nx.path_graph(8)
nx.draw(G, font_size=14, with_labels=True)
plt.savefig("simple_path.png") # save as png
plt.show() # display
import pylab
import networkx as nx
G=nx.cycle_graph(40)
pos=nx.circular_layout(G)
#--- első
pylab.figure(1)
nx.draw(G, pos, node_color='#A0CBE2', node_size=400, font_size=24, with_labels=True)
#---második
pylab.figure(2)
nx.draw(G,pos, node_color='#A0CBA2',node_size=500, font_size=18, with_labels=True)
#--- Harmadikj
pylab.figure(3,figsize=(8,8))
nx.draw(G,pos, node_color='#A0ABA2' font_size=14, with_labels=True)
pylab.show()
G=nx.path_graph(5)
pos=nx.circular_layout(G)
nx.draw(G, pos, node_color='#A0ABA2', font_size=14, with_labels=True)
plt.show() # display
G=nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
G.add_cycle([0,1,2,3])
G.add_cycle([10,11,12],weight=7)
nx.draw(G, node_color='#10ABA2', font_size=14, with_labels=True)
pylab.show()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-61-0277d17aefc7> in <module> 1 G=nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc 2 ----> 3 G.add_cycle([0,1,2,3]) 4 G.add_cycle([10,11,12],weight=7) 5 AttributeError: 'Graph' object has no attribute 'add_cycle'
import networkx as nx
g = nx.DiGraph([('P', 'I0'), ('I0', 'I1'), ('I1', 'I2'),
('I2', 'I3'), ('I1', 'I5'), ('I5', 'C7'),
('C7', 'C6'), ('C6', 'I3'), ('I3', 'C9'),
('I3','I5')])
pos=nx.circular_layout(g)
nx.draw(g, pos, font_size=20, with_labels=True)
print('Hurok : ',list(nx.simple_cycles(g)))
pylab.show()
Hurok : [['C7', 'C6', 'I3', 'I5']]
options = {
'node_color': 'black',
'node_size': 100,
'width': 3,
}
G = nx.dodecahedral_graph()
shells = [[2, 3, 4, 5, 6], [8, 1, 0, 19, 18, 17, 16, 15, 14, 7], [9, 10, 11, 12, 13]]
nx.draw_shell(G, nlist=shells, **options , font_size=24, with_labels=True)
plt.show() # display
import matplotlib.pyplot as plt
import networkx as nx
%matplotlib inline
#graph object
g = nx.Graph()
#graph nodes
g.add_nodes_from(['s','a','b','c','g'])
#add edges
g.add_edge('s','a')
g.add_edge('s','b')
g.add_edge('a','b')
g.add_edge('a','c')
g.add_edge('a','g')
g.add_edge('b','c')
g.add_edge('c','g')
#labels
g.add_edge('s','a', weight=1)
g.add_edge('s','b', weight=4)
g.add_edge('a','b', weight=2)
g.add_edge('a','c', weight=5)
g.add_edge('a','g', weight=12)
g.add_edge('b','c', weight=2)
g.add_edge('c','g', weight=3)
# pos = nx.spring_layout(g)
fixed_positions = {'s':(0,4),'a':(4,6), 'b':(4,2), 'c':(8,4), 'g':(12,4)}#dict with two of the positions set
edge_labs = dict([( (u,v), d['weight']) for u,v,d in g.edges(data=True)])
nx.draw_networkx(g, fixed_positions )
nx.draw_networkx_edge_labels(g, fixed_positions, edge_labels=edge_labs)
nx.draw_networkx_nodes(g, fixed_positions, node_color='r')
plt.title("Egyszerű Graph")
plt.show()
print('shortest_path',nx.shortest_path(g,'s','g'))
print('dijkstra_path', nx.dijkstra_path(g, 's','g'))
print('astar_path',nx.astar_path(g,'s', 'g', heuristic = None ))
shortest_path ['s', 'a', 'g'] dijkstra_path ['s', 'a', 'b', 'c', 'g'] astar_path ['s', 'a', 'b', 'c', 'g']
!conda install osmnx
!conda install -c conda-forge osmnx
^C
import networkx as nx
g = nx.DiGraph([('P', 'I0'), ('I0', 'I1'), ('I1', 'I2'),
('I2', 'I3'), ('I1', 'I5'), ('I5', 'C7'),
('C7', 'C6'), ('C6', 'I3'), ('I3', 'C9'),
('I3','I5')])
pos=nx.circular_layout(g)
nx.draw(g, with_labels=True)
plt.show()
from collections import defaultdict
class Graph():
def __init__(self,vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def isCyclicUtil(self, v, visited, recStack):
# Mark current node as visited and
# adds to recursion stack
visited[v] = True
recStack[v] = True
# Recur for all neighbours
# if any neighbour is visited and in
# recStack then graph is cyclic
for neighbour in self.graph[v]:
if visited[neighbour] == False:
if self.isCyclicUtil(neighbour, visited, recStack) == True:
return True
elif recStack[neighbour] == True:
return True
# The node needs to be poped from
# recursion stack before function ends
recStack[v] = False
return False
# Returns true if graph is cyclic else false
def isCyclic(self):
visited = [False] * self.V
recStack = [False] * self.V
for node in range(self.V):
if visited[node] == False:
if self.isCyclicUtil(node,visited,recStack) == True:
return True
return False
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 3)
g.addEdge(2, 3)
g.addEdge(3, 3)
if g.isCyclic() == 1:
print ("Graph has a cycle")
else:
print ("Graph has no cycle")
print(g)
Graph has a cycle <__main__.Graph object at 0x0000020AEA0872C8>
G3=nx.DiGraph()
f = open(r"SiouxFalls_flow.tntp", "r")
line = f.readline()
line = f.readline()
while len(line):
l = line.split()
fromnode = int(l[0])
to = int(l[1])
volume = float(l[2])
cost = int(float(l[3]))
G3.add_edge(fromnode, to, weight = cost)
line = f.readline()
f.close()
print(G3.number_of_edges())
f = open(r"SiouxFalls_node.tntp", "r")
line = f.readline()
line = f.readline()
while len(line):
line = line.strip(';')
l = line.split()
node = int(l[0])
pos1 = float(l[1])/10000
pos2 = float(l[2])/10000
G3.add_node(node, pos=(pos1,pos2))
line = f.readline()
f.close()
print(G3.number_of_nodes())
pos=nx.circular_layout(G3)
nx.draw(G3, with_labels=True)
plt.show()
76 24
G5.nodes[1]['pos'] = (0,0)
G5.nodes[2]['pos'] = (3,3)
G5.nodes[3]['pos'] = (3,-3)
G5.nodes[4]['pos'] = (6,0)
node_pos = nx.get_node_attributes(G5,'pos')
arc_cost = nx.get_edge_attributes(G5,'weight')
arc_cap = nx.get_edge_attributes(G5,'capacity')
node_col = ['blue']
nx.draw_networkx(G5, node_pos,node_color= node_col, node_size=450)
nx.draw_networkx_labels(G5, node_pos, node_color=['blue'])
nx.draw_networkx_edges(G5, node_pos)
nx.draw_networkx_edge_labels(G5, node_pos,edge_labels=optimal_flow)
# Remove the axis
plt.axis('off')
# Show the plot
print("The edge weights correspond to optimal flow values:")
plt.figure(figsize=(7,5))
#nx.draw(G5)
plt.show()
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-88-fe52e52178f8> in <module> 11 nx.draw_networkx_labels(G5, node_pos, node_color=['blue']) 12 nx.draw_networkx_edges(G5, node_pos) ---> 13 nx.draw_networkx_edge_labels(G5, node_pos,edge_labels=optimal_flow) 14 # Remove the axis 15 plt.axis('off') NameError: name 'optimal_flow' is not defined