Looking to add a legends using arcpy

5639
4
01-11-2014 10:45 PM
swatisaini
New Contributor
Hi,

I am trying to add a legend to a map layout using arcpy. after going through the tutorials I have used the following code :
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
lyrFile = arcpy.mapping.Layer(r"C:\Project\Data\Rivers.lyr")
arcpy.mapping.AddLayer(df, lyrFile, "TOP")
styleItem = arcpy.mapping.ListStyleItems("USER_STYLE", "Legend Items", "NewDefaultLegendStyle")[0]
legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")[0]
legend.updateItem(lyrFile, styleItem)
del mxd


but everytime I run this code I found an error :

Runtime error
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'list' object has no attribute 'updateItem'


Kindly help to resolve this.
I am new to map automation and using Python.

Thanks
Swati
0 Kudos
4 Replies
JeffBarrette
Esri Regular Contributor
The code sample you have below is identical to the help sample for the Legend Class.  I don't see any changes and wonder if your data supports these lines of code.  Is this the actual code you are running aginst your data.

I'm confused by the error.  This line should return a proper legend element, if one exists:
legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")[0]



Jeff
0 Kudos
swatisaini
New Contributor
Hi,

Yes, the code is same as is given in the Arcgis 10.1 Help as a sample code and i tired running this after creating a same folder ,Layer and mxd.But After i ran this code it gave me the following error:
Runtime error
Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: 'list' object has no attribute 'updateItem'

Can;t figure out what I am doing wrong. However, my aim is to add legend to the map (around 50 maps) and the legend is different for each of the map.Kindly tell me what should i do to automate this.

Is there a way to save a legend file , so that we can add it using arcpy..???
Thanks,
Swati
0 Kudos
JeffBarrette
Esri Regular Contributor
I can't see the error in your code.  Are you running this from ArcMap?

You can NOT create new legends with arcpy.mapping.  You can only alter existing legends on a page layout.  If you add layers to a data frame, those layers can automatically be added to the legend.  You can control column count, positioning, etc

Jeff
0 Kudos
AlexCarrier2
New Contributor

Can you control font size/style in a legend with arcpy?

0 Kudos