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?
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.
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