6

I want to be able to label point features on my map in a python loop.

How do I access the ArcGIS label engine with ArcPy?

2 Answers 2

8

I've never tried labeling through arcpy myself, but it appears that you can enable and edit labels via the arcpy.mapping module as described here. The basics of the mapping module are:

1) Create a reference to a map document (if it is open in ArcMap, you can use "CURRENT")
2) Create a reference to the data frame(s) in the map document (optional)
3) Create a reference to the layer(s) in the data frame(s)

These references all act as objects which can be used in any geoprocessing as inputs and outputs as long as they are of the proper type. Initially they will be lists, so be sure to INDEX the reference! For labeling, if you know exactly which layer you want to label, it appears that you could use the following code:

import arcpy
mxd = arcpy.mapping.MapDocument(r"Mypathhere") #Map document reference
layer = arcpy.mapping.ListLayers(mxd, "Layername")[0] #Indexing list for 1st layer
if layer.supports("LABELCLASSES"):
    for lblclass in layer.labelClasses:
        lblclass.className = "Class Name Here"
        lblclass.expression = "Labeling expression here"
        lblclass.showClassLabels = True
mxd.save()
del mxd

And done. The arcpy.mapping module/class gives a ton of functionality for programmatic MXD customization. Give it a good looking over, I'm sure you will find it useful.

4
  • Thanks so much for the help, the arcpy.mapping module is really neat. I was able to label in python with your code just tweaked it a little bit. Thanks again
    – geoid
    Apr 5, 2011 at 18:08
  • @DJ Martin Glad it worked out for you. I edited my answer to show the right syntax (for posterity).
    – Nathanus
    Apr 5, 2011 at 18:18
  • this needs layer.showLabels = True before the mxd.save().
    – bananafish
    Jul 25, 2012 at 2:47
  • it seems that this part of ArcPy is not well documented, thanks a lot, is there any way to customize page size plz ?
    – geogeek
    Oct 30, 2013 at 17:19
2
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT") #Map document reference
layer = arcpy.mapping.ListLayers(mxd)[0] #Indexing list for 1st layer
if layer.supports("LABELCLASSES"):
    print "supported"
    for lblClass in layer.labelClasses:
        lblClass.className = "Class Name Here"
        lblClass.expression = "Labeling expression here"
        layer.showLabels = True
mxd.save()
del mxd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.