Sort the table
Having generated our sorted data, now let's display it.
Sorting the data makes the attribute table easier to read, but it doesn't give us an instant feel for the data. For this, we need to display the results, colour coded by risk in a classic choropleth map.
As it happens, this is surprisingly painful in Arc with Python. The reason is that the symbolism of layers isn't entirely exposed in the Python API (indeed, it isn't well exposed in other languages either). I'm guessing ESRI have their reasons for this, but if they do, they're not obvious. Anyhow, the short of it is, instead of making new symbols/colours etc. for layers shown in ArcMap, you have to copy a type of symbolism out of another layer, and then adapt what you've copied. This means that at some point you have to start this chicken-and-egg business by manually making a layer with the right symbolism type. This, to finally come back to it, is why there is a "buildings.lyr" file in the zipfile. This is the buildings shapefile as a layer, in which we've manually set the symbolism. We can copy this into a new layer showing our new data. It has to be said that working out how to do this isn't simple, so here's the code. Add it to the end of TraffordModelScript.py:
mxd = arcpy.mapping.MapDocument("CURRENT")
df = mxd.activeDataFrame
newlayer = arcpy.mapping.Layer("crime_sorted.shp")
layerFile = arcpy.mapping.Layer("albertsquare/buildings.lyr")
arcpy.mapping.UpdateLayer(df, newlayer, layerFile, True)
newlayer.symbology.valueField = "Join_Count"
newlayer.symbology.addAllValues()
arcpy.mapping.AddLayer(df, newlayer,"TOP")
A few things to note about this. The first is that this assumes TraffordModelScript.py is in the directory m:/GEOG5790M/practical4/ within which is also a m:/GEOG5790M/practical4/albertsquare directory containing the buildings.lyr: note the use of the relative address. The second is that we add the new layer to the TOP of the table of contents, so it's colours are those the user sees, and it isn't hidden under other layers.
Secondly the algorithm is:
Get the current map document.
Get that bit of it currently showing (there might be multiple "maps" in this document in layout view).
Make a new layer from the data.
Make a new layer from the example layer file.
Update the data layer with the symbolism from the example.
Say that we want it coloured by the values in the "Joint_Count" column.
Add all the unique Joint_Count values to the symbolism (otherwise it just displays one colour).
Add the data layer to the map at the TOP.
Hopefully that all now works. If it does, congrats, you're done!