How do I apply a style file to a field in a feature layer?

1141
1
09-04-2014 09:46 PM
AllanMills
New Contributor III

I've got a style file which I'm trying to apply to a feature class and create a .lyr file from it. There are multiple fields in the feature class which the style can be applied to. I just can't quite work out how to do this using python though.

Most example like the one on this page: ArcGIS Help 10.1  mentions using legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")[0] then using that object to modify the layer. But when I try that it doesn't find any legend elements. Even if it did, none of the examples mention how to apply it to a specific field.

I also tried using an existing .lyr file with the same style applied then using ApplySymbologyFromLayer to copy it over. That works, but I can't modify the symbology to change the field it has been applied to.

0 Kudos
1 Reply
NaimeCelik
Occasional Contributor

I had a similar problem. I had a style file and I could not  use it with python. To make Legend appear you need to include a empty legend on the mxd. Therefore, no legend items comes up.

To apply style, I could not find any tool but I used ApplySymbologyFromLayer. What you need to do is you need to arrange your sembology layer as you want and then you need to indicate label expression (Field name that your sembology need to use)   the line below (lyr1.labelClasses[0].expression = LabelExpression)

Here a script that I used to make a tool. After getting label name as text you need to get it to be brackets []

import arcpy,os

symbologyLayer=arcpy.GetParameterAsText(2)

LabelExpression=arcpy.GetParameterAsText(1)

try:

for idx, item in enumerate(LabelExpression.split()):

    if 'VISIBLE'==item:

            num=idx

            arcpy.AddWarning(LabelExpression.split()[idx-1])

LabelExpression="["+LabelExpression.split()[num-1]+"]"

except:

      arcpy.AddError("Choose only one field name for label expession")

           

K_shp=arcpy.GetParameterAsText(0)

add_legend= arcpy.GetParameterAsText(3)

LayerName=os.path.split(K_shp)[1][:-4]+"_lyr"

mxd = arcpy.mapping.MapDocument("CURRENT")  

df = arcpy.mapping.ListDataFrames(mxd)[0]

arcpy.MakeFeatureLayer_management(K_shp,LayerName)

lyr1= arcpy.mapping.Layer(LayerName)

arcpy.ApplySymbologyFromLayer_management (lyr1, symbologyLayer)

lyr1.labelClasses[0].expression = LabelExpression

lyr1.showLabels = True

arcpy.RefreshActiveView()

arcpy.mapping.AddLayer(df, lyr1, "BOTTOM")

if add_legend=='true':

    #styleItem = arcpy.mapping.ListStyleItems("USER_STYLE", "Legend Items", "NewDefaultLegendStyle")[0]

    legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "Legend")[0]

    #legend.updateItem(lyr1, styleItem)

    legend.autoAdd = True

   

del mxd   

0 Kudos