# 克努斯英里¶

miles_graph() 从数据文件返回128个美国城市的无向图 miles_dat.txt . 每个城市都有位置和人口数据。边缘标有两个城市之间的距离。

## 参考文献。¶

1

Donald E.Knuth，“斯坦福图形：组合计算平台”，ACM出版社，纽约，1993年。

2

http://www cs faculty.stanford.edu/~knuth/sgb.html

Loaded miles_dat.txt containing 128 cities.
digraph has 128 nodes with 8128 edges


# Author: Aric Hagberg (hagberg@lanl.gov)

#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>

import re
import sys

import matplotlib.pyplot as plt
import networkx as nx

def miles_graph():
""" Return the cites example graph in miles_dat.txt
from the Stanford GraphBase.
"""
# open file miles_dat.txt.gz (or miles_dat.txt)
import gzip
fh = gzip.open('knuth_miles.txt.gz', 'r')

G = nx.Graph()
G.position = {}
G.population = {}

cities = []
line = line.decode()
continue

numfind = re.compile("^\d+")

if numfind.match(line):  # this line is distances
dist = line.split()
for d in dist:
i = i + 1
else:  # this line is a city, position, population
i = 1
(city, coordpop) = line.split("[")
cities.insert(0, city)
(coord, pop) = coordpop.split("]")
(y, x) = coord.split(",")

# assign position - flip x axis for matplotlib, shift origin
G.position[city] = (-int(x) + 7500, int(y) - 3000)
G.population[city] = float(pop) / 1000.0
return G

if __name__ == '__main__':

G = miles_graph()

print("digraph has %d nodes with %d edges"
% (nx.number_of_nodes(G), nx.number_of_edges(G)))

# make new graph of cites, edge if less then 300 miles between them
H = nx.Graph()
for v in G:
for (u, v, d) in G.edges(data=True):
if d['weight'] < 300:

# draw with matplotlib/pylab
plt.figure(figsize=(8, 8))
# with nodes colored by degree sized by population
node_color = [float(H.degree(v)) for v in H]
nx.draw(H, G.position,
node_size=[G.population[v] for v in H],
node_color=node_color,
with_labels=False)

# scale the axes equally
plt.xlim(-5000, 500)
plt.ylim(-2000, 3500)

plt.show()


Total running time of the script: ( 0 minutes 0.279 seconds)

Gallery generated by Sphinx-Gallery