Advanced label expression by arcpy

12-21-2015 06:50 PM
New Contributor

I would like to use arcpy to add a specific layer in mxd and automatically label the feature with different colors according to its attributes.

Even if I use the simple syntax lblClass.expression = "Function FindLabel ( [OBJECTID] ) FindLabel = [OBJECTID] End Function", label also cannot be shown. I search some papers about this and found that it may caused by "Advanced" setting on label expression. However, my layer is dynamically added in mxd but not pre-loaded in mxd.

Does anyone know,

1)  Can I label the feature with different colors according to its attributes if i don't turn on "Advanced" setting on label expression (dont use If-then)?

2)  How can I turn on the "Advanced" label expression by using arcpy? As I know, there is no property of labelClass to turn on the "Advanced" mode. Any other alternative methods to do so? I tried to use arcpy.mapping.UpdateLayer but "Advanced" label expression can not be updated by other layers which have set the "Advanced" option.


0 Kudos
2 Replies
New Contributor III

I just ran to the same problem where I could not tick the Advanced box in the Label Expression using ArcPy.  Here's a simple workaround:

Add another column in the feature class for the label expression.  Use the Field Calculator with your label expression to update the label column.  This can all be done via ArcPy.

0 Kudos
MVP Regular Contributor

There are no properties documented to select the advanced option or parser for the LabelClass.  You can use some Formatting tags in your labels to display color.

You might use the Field Calculator to populate a second label field with text that includes color tags, such as:

# code block
def colorLabel(attrib, label):
    if attrib == 1:
        return '<CLR red = "255">{}</CLR>'.format(label)
    elif attrib == 2:
        return '<CLR blue = "255">{}</CLR>'.format(label)
    elif attrib == 3:
        return '<CLR red = "255" green = "255">{}</CLR>'.format(label)
        return label

# expression
colorLabel(!AttributeField!, !LabelField!)‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos