← Back to Archives

An Improvement to FlowingData's Choropleth Tutorial

elections

Nathan Yau at FlowingData has a very cool tutorial that shows how to make a choropleth graph of county-level data in the U.S. The end result looks something like this:

Joe's 2009 Unemployment Choropleth (an image of the U.S. in shades of blue that highlight the rate of unemployment)

Cool!

One problem with the tutorial as written is that it doesn't output an SVG file that will actually display. As other commenters noticed, the python xml parsing library BeautifulSoup was attempting to close two tags, <defs ... /> and <sodipodi:namedview ... />, that don't need closing. The comments suggest editing by hand... there must be a better way!

It turns out that the solution is easy. You can tell BeautifulSoup that certain tags are "self-closing". So, in the tutorial code, replace the line:

soup = BeautifulSoup(svg)

with

soup = BeautifulSoup(svg, selfClosingTags=['defs','sodipodi:namedview'])

and the resulting SVG will display just fine.