Skip to content

Instantly share code, notes, and snippets.

@avaccari
Last active November 6, 2020 07:28
Show Gist options
  • Save avaccari/80c34d561d013483bec9 to your computer and use it in GitHub Desktop.
Save avaccari/80c34d561d013483bec9 to your computer and use it in GitHub Desktop.
Arcpy: programmatically adding labels to layers using fields values
# Import arcpy
import arcpy as ap
# Load the reference to the current map document.
# Caveat: not sure it will work if the toolbox is running in background.
# This is because background execution is performed within a separate
# kernel.
mxd = ap.mapping.MapDocument("CURRENT") # (mxd_path)
# Get list of dataframes. There might be more than one dataframe in a map
# document. You can use the wildcard to specify which one is of interest.
# Here we are "blindly" extracting the first element in the returned list
dfs = ap.mapping.ListDataFrames(mxd, "") # (map_document, {wildcard})
df = dfs[0]
# Get list of layers. Once again there might be more than one layer within
# the selected dataframe. Wildcard can be used to specify the subset or
# specific one. Once again we are "blindly" using the first one.
lyrs = ap.mapping.ListLayers(mxd, "", df) # (map_document_or_layer, {wildcard}, {data_frame})
lyr = lyrs[0]
# Check if the layer support label classes
if lyr.supports("LABELCLASSES"):
# Get list of labelClasses. There might be more than one label class.
# We are selecting/defining the first.
lcs = lyr.labelClasses
lc = lcs[0]
# Define the expression to use. Here we are using the attributes
# [HEIGHT] and [VEL] from the display data table.
# Notes:
# - switching ' with " didn't work
# - inserting escaped characters such as '\n' did not work
lc.expression = '[HEIGHT] + "m, " + [VEL] + "mm/yr"'
# Turn the labels on for the entire layer.
lyr.showLabels = True
# Refresh the current view
ap.RefreshActiveView()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment