I want to be able to check if a layer is visible in the legend and if so then perform another operation - in python. I am using ArcGIS 10.2 for Desktop.
I cannot find anywhere how to check if a layer is visible or not in the legend.
1 Answer 1
Assuming that you mean the visibility of the layer in the Table Of Contents, once you get a reference to the layer, it has a visible
attribute:
import arcpy
inMXD = "xyz.mxd"
lyrName = "layername"
mxd = arcpy.mapping.MapDocument(inMXD)
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] #the first data frame
lyr = arcpy.mapping.ListLayers(mxd, lyrName, df)[0]
if(lyr.visible):
print(lyr.name + " is visible")
else:
print(lyr.name + " is not visible")
If the visibility of the layer in the Legend does not match the visibility in the Table Of Contents, you can use listLegendItemLayers ():
legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "Legend")[0]
legendLayers = legend.listLegendItemLayers()
for idx in range(0, len(legendLayers)):
legendLayer = legendLayers[idx]
legendVisibility = legendLayer.visible
if(legendVisibility == 0):
print(legendLayer.name + " is not visible on the legend")
else:
print(legendLayer.name + " is visible on the legend")