Select to view content in your preferred language

Labels Still Not Visible after setting lyr.labelClasses[0].showLabels = True

5876
20
Jump to solution
12-24-2013 10:05 AM
JonathanMulder
Occasional Contributor
Thanks to an earlier reply today, I'm moving along on my script but have encountered another hiccup.

I've set "lyr.showLabels = True".  After looking through some other threads, it looks like I also need to set labelClasses to "showLabels = True".  The script runs with no errors but does not show the labels.  When clicking on layer properties|Labels, it shows that the labelClasses[0].expression DID accept the StateWellNumber field.  But the checkbox for showing labels is not checked.

Is this "par for the course"?  Not a big deal (I can just go in and fill the checkbox), but it would be nice to see the labels come in as the script runs.

Thanks,

Jon Mulder 



LayerFileLocation = "H:\Documents\GIS\HydstraData" LayerName = "WellPoints.lyr" ##Define layer: lyr = arcpy.mapping.Layer(os.path.join(LayerFileLocation,LayerName)) arcpy.AddMessage(lyr) ##Show labels for WellPoints. lyr.supports("LABELCLASSES") lyr.showLabels = True lyr.labelClasses[0].expression =  "StateWellNumber" lyr.labelClasses[0].showLabels = True arcpy.RefreshActiveView()
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
T__WayneWhitley
Honored Contributor
Jon, I received the data and corrected the script - only where the labeling is concerned for the well points layer.

First of all, the file gdb labeling does indeed use brackets...the field must be referenced - I should've known actually the text I had you insert would actually be interpreted as raw text, i.e. every label would simply be the text, StateWellNumber, lol!  That was my mistake...but not the primary problem.  Your problem was the labels wouldn't turn on.

Just before Jeff's post you made a statement that turns out after further testing to be essentially true:
"Could it be that my "wells_lyr" variable near the bottom of my code does not actually refer to the "AllPoints" layer (i.e. Featureclass) in the map?"

Nice catch - so the fix was to manipulate the labeling before adding the layer to the map.  I don't know if this is a design feature or a bug, but at least there's a relatively simple workaround...I sent you the script pared down to a few lines designed for you to simply load and run in ArcMap to see it in action.  The relevant lines I'll post below:
WellPtsLyrFile = os.path.join(rootPath, 'WellPoints201312271743.lyr') Wells_lyr = arcpy.mapping.Layer(WellPtsLyrFile)  ##Show labels for WellPoints. if Wells_lyr.supports("LABELCLASSES"):     Wells_lyr.labelClasses[0].expression =  "[StateWellNumber]"      ## class labeling is on by default; showClassLabels is optional.     #Wells_lyr.labelClasses[0].showClassLabels = True     Wells_lyr.showLabels = True  arcpy.mapping.AddLayer(df, Wells_lyr, "AUTO_ARRANGE")


Hope that finally clears up any lingering confusion.  Actually the showClassLabels property I can see could be pretty useful, say if you defined multiple label classes in a single layer file, then wanted to run for example multiple PDF exports showing only certain label classes...with them already defined, all you'd have to manage is switching them on/off as needed in a loop to produce your PDF pages.  (Or, say you had multiple data frames - same principle applies, using the same lyr file but managing labeling in various different ways for each data frame.)

Wayne

View solution in original post

0 Kudos
20 Replies
T__WayneWhitley
Honored Contributor
The layer hasn't been added to the map...you can use the addLayer function or the updateLayer function in conjunction with ListLayers to get a reference to a layer already in the map.  Or to update the layer file, save or otherwise overwrite the file on disk.
0 Kudos
JonathanMulder
Occasional Contributor
Ah!  Thanks for the tip!  I'll check it out soon, but right now, it's eggnog time.

Happy Holidays!

Jon Mulder
Durham, California
0 Kudos
JonathanMulder
Occasional Contributor
Actually, I HAVE added layers, I think.

My workflow is:
Add layer (Actually a Feature class in a Geodatabase)
Symbolize Featureclass based on .lyr file previously saved.
Show labels for my WellPoint Featureclass.

Could it be that my "wells_lyr" variable near the bottom of my code does not actually refer to the "AllPoints" layer (i.e. Featureclass) in the map?

Jon Mulder


import arcpy
import arcpy.mapping
import os
OutFolderPath = "H:\Documents\GIS\HydstraData\HydstraMeasurementsDeep"
GeoDatabaseName = "HydstraMeasurementsDeep_GroundwaterElevation_Daily_Contours_20130625_20131015.gdb"
LayerFileLocation = "H:\Documents\GIS\HydstraData"

##Reference the Current map document.
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]

##arcpy.env.workspace = GeoDatabaseName
arcpy.env.workspace = "H:\Documents\GIS\HydstraData"

##Add AllPoints Featureclass to map.
Wells_lyr = os.path.join(OutFolderPath,GeoDatabaseName,"AllPoints")
##print Wells_lyr
arcpy.AddMessage(Wells_lyr)
Wells_lyr = arcpy.mapping.Layer(Wells_lyr)
arcpy.mapping.AddLayer(df, Wells_lyr, "AUTO_ARRANGE")

##Add AllContours3D Featureclass to map.
Contours_lyr = os.path.join(OutFolderPath,GeoDatabaseName,"AllContours3D")
##print Contours_lyr
arcpy.AddMessage(Contours_lyr)
Contours_lyr = arcpy.mapping.Layer(Contours_lyr)
arcpy.mapping.AddLayer(df, Contours_lyr, "AUTO_ARRANGE")

##Apply symbology from layer files.
LayerName = os.path.join(LayerFileLocation,"CasedContours.lyr")
arcpy.AddMessage(LayerName)
arcpy.ApplySymbologyFromLayer_management("AllContours3D",LayerName)
LayerName = os.path.join(LayerFileLocation,"WellPoints.lyr")
arcpy.ApplySymbologyFromLayer_management("AllPoints",LayerName)
arcpy.RefreshTOC()
arcpy.RefreshActiveView()

##Show labels for WellPoints.
Wells_lyr.supports("LABELCLASSES")
Wells_lyr.showLabels = True
Wells_lyr.labelClasses[0].expression =  "StateWellNumber"
Wells_lyr.labelClasses[0].showLabels = True
arcpy.RefreshTOC()
arcpy.RefreshActiveView()
0 Kudos
JeffBarrette
Esri Regular Contributor
Try changing:
Wells_lyr.labelClasses[0].showLabels = True


to

Wells_lyr.labelClasses[0].showClassLabels = True


The Layer object has the property showLabels
The LabelClass object has the showClassLabels property.

Jeff
0 Kudos
JonathanMulder
Occasional Contributor
Thanks, Jeff.  I gave that a try.  Everything runs (no errors), but labels still do not appear...

They DO appear if I go into TOC, right-click on layer and enable checkbox for Show Labels.
0 Kudos
T__WayneWhitley
Honored Contributor
Simple error I believe with the label expression - the label engine needs the brackets:
Wells_lyr.labelClasses[0].expression =  "[StateWellNumber]"


...and if you only have the 1 label class, i.e. the default, you can simply toggle the 'label features' from the layer level, as in:
Wells_lyr.showLabels = True


You already have that in the code, correctly followed by RefreshActiveView.  If you have multiple class labels, then as Jeff was saying you can selectively toggle those individual classes on/off -- but you still have the need the lyr.showLabels to 'globally' turn on/off the labeling engine for the layer - in other words, enable the labeling for those classes you've allowed it for [at the labelClasses level].  Note that you can have labelClasses showClassLabels set to True and still choose to show no labels at all via your Wells_lyr.showLabels = False

Hope that helps.

Wayne


EDIT:
oops, in my test I wasn't sourced to a file gdb fc, so if you are pointed to a file gdb source, then the webhelp suggests you need double-quotes on the expression -- so try this:
Wells_lyr.labelClasses[0].expression =  "\"StateWellNumber\""


...see this (LabelClass example 2, at the bottom of the page):

LabelClass (arcpy.mapping)
Desktop » Geoprocessing » ArcPy » Mapping module
http://resources.arcgis.com/en/help/main/10.2/index.html#//00s30000002t000000
0 Kudos
JonathanMulder
Occasional Contributor
Wayne,

Thanks for your response.  I didn't realize about that convoluted syntax for accessing a field name in a geodatabase.  My code runs with no errors but labels still do not appear.

I added a snippet of code toward the bottom to print out some layer properties.  Based on my results, it still evaluates "lyr.supports("LABELCLASSES")" as False, because it doesn't proceed into the if statement.

Jon Mulder


Executing: UpdateMap
Start Time: Fri Dec 27 07:21:29 2013
Running script UpdateMap...
H:\Documents\GIS\HydstraData\HydstraMeasurementsDeep\GSE_Daily_Contours_20130625_20131015.gdb\WellPoints
H:\Documents\GIS\HydstraData\HydstraMeasurementsDeep\GSE_Daily_Contours_20130625_20131015.gdb\AllContours3D
H:\Documents\GIS\HydstraData\CasedContours.lyr
Layer name: WellPoints
Layer name: AllContours3D
Completed script UpdateMap...
Succeeded at Fri Dec 27 07:21:34 2013 (Elapsed Time: 4.77 seconds)


import arcpy
import arcpy.mapping
import os
OutFolderPath = "H:\Documents\GIS\HydstraData\HydstraMeasurementsDeep"
GeoDatabaseName = "GSE_Daily_Contours_20130625_20131015.gdb"
LayerFileLocation = "H:\Documents\GIS\HydstraData"

##Reference the Current map document.
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]

ws = os.path.join(OutFolderPath,GeoDatabaseName)
arcpy.env.workspace = ws
arcpy.AddMessage(ws)
##arcpy.env.workspace = "H:\Documents\GIS\HydstraData"

##Add AllPoints Featureclass to map.
Wells_lyr = os.path.join(OutFolderPath,GeoDatabaseName,"WellPoints")
##print Wells_lyr
arcpy.AddMessage(Wells_lyr)
Wells_lyr = arcpy.mapping.Layer(Wells_lyr)
arcpy.mapping.AddLayer(df, Wells_lyr, "AUTO_ARRANGE")

##Add AllContours3D Featureclass to map.
Contours_lyr = os.path.join(OutFolderPath,GeoDatabaseName,"AllContours3D")
##print Contours_lyr
arcpy.AddMessage(Contours_lyr)
Contours_lyr = arcpy.mapping.Layer(Contours_lyr)
arcpy.mapping.AddLayer(df, Contours_lyr, "AUTO_ARRANGE")

##Apply symbology from layer files.
LayerName = os.path.join(LayerFileLocation,"CasedContours.lyr")
arcpy.AddMessage(LayerName)
arcpy.ApplySymbologyFromLayer_management("AllContours3D",LayerName)
LayerName = os.path.join(LayerFileLocation,"WellPoints.lyr")
arcpy.ApplySymbologyFromLayer_management("WellPoints",LayerName)
arcpy.RefreshTOC()
arcpy.RefreshActiveView()

##Show labels for WellPoints.
arcpy.AddMessage(Wells_lyr)
Wells_lyr.supports("LABELCLASSES")
Wells_lyr.showLabels = True
Wells_lyr.labelClasses[0].expression =  "\"StateWellNumber\""
Wells_lyr.labelClasses[0].showClassLabels = True

arcpy.RefreshActiveView()
for lyr in arcpy.mapping.ListLayers(mxd):
    arcpy.AddMessage( "Layer name: " + lyr.name)
    if lyr.supports("LABELCLASSES"):
        if lyr.showLabels:
            arcpy.AddMessage( "Layer name: " + lyr.name)
            for lblClass in lyr.labelClasses:
                if lblClass.showClassLabels:
                    arcpy.AddMessage( "   Class Name:  " + lblClass.className)
                    arcpy.AddMessage("    Expression:  " + lblClass.expression)
                    arcpy.AddMessage("    SQL Query:   " + lblClass.SQLQuery)
0 Kudos
T__WayneWhitley
Honored Contributor
Interesting - probably better to troubleshoot within ArcMap's Python window so that you'd get more informative messages back, but since you've already made this a script tool, try replacing your ListLayers section of code with the snippet below and see what messages you get back.  A confusing little thing you coded that is making this a little trickier is you have 2 identical messages printing; the 2nd one isn't printing obviously but you have 2 'if' statements to eval to true in order for the 2nd one to print --- so you still don't really know what's up....need more feedback - if the below doesn't work to at least give you a better lead (this is not a solution, just an attempt to get back more of a clue), try attaching a gdb sample of your layers if you can for someone to work with.  You are working with 10.2?  I realize you are new to this; someone can write shorter more concise code for you to study/test/etc.
for lyr in arcpy.mapping.ListLayers(mxd):
    arcpy.AddMessage( "Layer name: " + lyr.name)
    if lyr.supports("SHOWLABELS"):
            arcpy.AddMessage(lyr.name + " supports labeling.")
            arcpy.AddMessage("Layer labeling is on?:  " + str(lyr.showLabels))
            for lblClass in lyr.labelClasses:
                arcpy.AddMessage( "   Class Name:  " + lblClass.className)
                arcpy.AddMessage("    Expression:  " + lblClass.expression)
                arcpy.AddMessage("    SQL Query:   " + lblClass.SQLQuery)
                arcpy.AddMessage("Label class is on?:   " + str(lblClass.showClassLabels))
0 Kudos
JonathanMulder
Occasional Contributor
Thanks Wayne,

I'll give it a try in a little bit.  Currently, I have two other ArcMap sessions running on imagery processing.

Yes, I'm using 10.2 version (Home Use license from about 45 days ago.

Question -- Why is the fourth line indented an additional 8 spaces and not 4?

I took the 3-day scripting course about 2 months ago in Sacramento (Jeff Bilos(?)).  I didn't learn much about the Python window.  How could I query in the window if the "lyr.supports("SHOWLABELS")"?  I assume that's what you alluding to...

Jon Mulder
0 Kudos