Statistics
| Branch: | Revision:

iof-tools / networkxMiCe / networkx-master / examples / drawing / plot_knuth_miles.py @ 5cef0f13

History | View | Annotate | Download (2.83 KB)

1
#!/usr/bin/env python
2
"""
3
===========
4
Knuth Miles
5
===========
6

7
`miles_graph()` returns an undirected graph over the 128 US cities from
8
the datafile `miles_dat.txt`. The cities each have location and population
9
data.  The edges are labeled with the distance between the two cities.
10

11
This example is described in Section 1.1 in Knuth's book (see [1]_ and [2]_).
12

13
References.
14
-----------
15

16
.. [1] Donald E. Knuth,
17
   "The Stanford GraphBase: A Platform for Combinatorial Computing",
18
   ACM Press, New York, 1993.
19
.. [2] http://www-cs-faculty.stanford.edu/~knuth/sgb.html
20

21

22
"""
23
# Author: Aric Hagberg (hagberg@lanl.gov)
24

    
25
#    Copyright (C) 2004-2019 by
26
#    Aric Hagberg <hagberg@lanl.gov>
27
#    Dan Schult <dschult@colgate.edu>
28
#    Pieter Swart <swart@lanl.gov>
29
#    All rights reserved.
30
#    BSD license.
31

    
32
import re
33
import sys
34

    
35
import matplotlib.pyplot as plt
36
import networkx as nx
37

    
38

    
39
def miles_graph():
40
    """ Return the cites example graph in miles_dat.txt
41
        from the Stanford GraphBase.
42
    """
43
    # open file miles_dat.txt.gz (or miles_dat.txt)
44
    import gzip
45
    fh = gzip.open('knuth_miles.txt.gz', 'r')
46

    
47
    G = nx.Graph()
48
    G.position = {}
49
    G.population = {}
50

    
51
    cities = []
52
    for line in fh.readlines():
53
        line = line.decode()
54
        if line.startswith("*"):  # skip comments
55
            continue
56

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

    
59
        if numfind.match(line):  # this line is distances
60
            dist = line.split()
61
            for d in dist:
62
                G.add_edge(city, cities[i], weight=int(d))
63
                i = i + 1
64
        else:  # this line is a city, position, population
65
            i = 1
66
            (city, coordpop) = line.split("[")
67
            cities.insert(0, city)
68
            (coord, pop) = coordpop.split("]")
69
            (y, x) = coord.split(",")
70

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

    
77

    
78
if __name__ == '__main__':
79

    
80
    G = miles_graph()
81

    
82
    print("Loaded miles_dat.txt containing 128 cities.")
83
    print("digraph has %d nodes with %d edges"
84
          % (nx.number_of_nodes(G), nx.number_of_edges(G)))
85

    
86
    # make new graph of cites, edge if less then 300 miles between them
87
    H = nx.Graph()
88
    for v in G:
89
        H.add_node(v)
90
    for (u, v, d) in G.edges(data=True):
91
        if d['weight'] < 300:
92
            H.add_edge(u, v)
93

    
94
    # draw with matplotlib/pylab
95
    plt.figure(figsize=(8, 8))
96
    # with nodes colored by degree sized by population
97
    node_color = [float(H.degree(v)) for v in H]
98
    nx.draw(H, G.position,
99
            node_size=[G.population[v] for v in H],
100
            node_color=node_color,
101
            with_labels=False)
102

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

    
107
    plt.show()