10.2. Using shapefiles

This section provides a very brief introduction to some google tools for using shapefiles which allow various kinds of data to be visualized on a map.

10.2.1. What are shapefiles?

The shapefile format is one of a number of formats for representing boundaries and areas on maps.

10.2.2. Example

The following example uses the Federal elections data from Aggregation, imported in the first lines.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
     }

from compute_donations import percent
# We'll visualize the percentages as percent of total contribs going to Obama
# obama is a dictionary: StateCode => percentages of contribs to Obama in State
obama = percent['Obama, Barack']

# We have 50 state shapes to iterate through
for record, shape in zip(records,shapes):
    lons,lats = zip(*shape.points)
    # For n points, we need an n x 2 array
    data = np.array(m(lons, lats)).T
 
    if len(shape.parts) == 1:
        segs = [data,]
    else:
        segs = []
        for i in range(1,len(shape.parts)):
            index = shape.parts[i-1]
            index2 = shape.parts[i]
            segs.append(data[index:index2])
        segs.append(data[index2:])

 
    lines = LineCollection(segs,antialiaseds=(1,))

    try:
        # record[1] is the state name for this shape.
        # map it to a state code: state_to_code[record[1]]
        # map the result to a percentage: obama[  ] 
        per = obama[state_to_code[record[1]]]
    except KeyError:
        print 'No donation state: %s' % record[1]