[GIS] Resequencing Legend Items using ArcPy

arcgis-10.0arcpylegend

I create various layers programmatically using ArcPy.

I can adjust how the layers are sequenced using the arcpy.mapping.MoveLayer command.

However, I want to have the legend reflect a different order. I have yet to figure out how to do this in Python.

I have tried using legend.autoAdd=True or False. I think I am close in using:

legend=arcpy.mapping.ListLayoutElements(mxd,"LEGEND_ELEMENT","My Legend") [0]

and then legend.items.something.

I have four legend items A, B, C, and D which appear incorrectly as D, C, A, B.

Can anyone provde a link to code examples or better documentation?


This question was originally posed for ArcGIS 10.0 but another question (Moving legend items up and down with arcpy) using ArcGIS 10.2 has been merged into it so answers using any version from and including 10.0 should be acceptable.

Best Answer

With the AddLayer method you cannot be more precise than "TOP" or "BOTTOM" as shown above.

However, if you use the InsertLayer method (ESRI Help Pages), you can specify a reference layer (or multiple reference layers) and add your new layer in reference to that.

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "County Maps")[0]
refLayer = arcpy.mapping.ListLayers(mxd, "Lakes", df)[0]
insertLayer = arcpy.mapping.Layer(r"C:\Project\Data\Rivers.lyr")
arcpy.mapping.InsertLayer(df, refLayer, insertLayer, "BEFORE")
mxd.saveACopy(r"C:\Project\Project2.mxd")
del mxd, insertLayer
Related Question