
198
|
Chapter 4, Mapping (on) the Web
#44 Plot Statistics Against Shapes
HACK
You can also use it to plot specific values using a color palette that you sup-
ply. The first technique is the more useful here.
For this hack, we’ve provided a sample shapefile, voting precincts in San
Francisco as of 2003, and an Excel file that has data that maps to it. You
should be able to use any freely available political shape you find, if you can
find or create statistics that share a key column with it.
SVG::Shapefile reads
.csv and .xls files using the Perl DBI interface, so you can hook it up directly
to an SQL database if you want.
The Code
This script assumes you have the zipped-up shapefile and the Excel file in
the same directory you run it from. Get them from http://mappinghacks.com/
data/PRECINCTS.zip and http://mappinghacks.com/data/SF_runoff.xls. Type
unzip PRECINCTS.zip to extract the contents of the shapefile, and then run
this script:
#!/usr/bin/perl
use strict;
use lib qw(/home/jo/indymapper);
use SVG::Shapefile;
my $svg = SVG::Shapefile->new(ShapeFile => 'PRECINCTS.shp',
PolygonID => 'PRECINCT',
DataFile => 'SF_runoff.xls',
KeyColumn => 'PRECINCTS',
ValueColumn => 'TURNOUT',
Colors => [[0,255,0],[255,0,0]]
);
$svg->render('map.svg');
Reading large shapefiles and converting them to SVG geometry can take
some time, so don’t worry if the script waits for quite a few seconds before
returning.
The
PolygonID