2

I have a blank map. And I have a shapefile. I would like to add the shapefile to the map document, change its colour to grey and then save the map document.

My plan is to make a layer from the shapefile (MakeFeatureLayer_management), add the resulting layer to the map document (mapping.AddLayer) and then change its colour using ApplySymbologyFromLayer_management.

This is my code so far:

import arcpy, os

### Set directory
arcpy.env.workspace = ...
arcpy.env.overwriteOutput = 1

### Define inputs
yellow = "symbology/yellow.lyr"

# Set map document
mxd_city_year = arcpy.mapping.MapDocument(r"...\blank_map.mxd")
DF = arcpy.mapping.ListDataFrames(mxd_city_year)[0]

# Add layers
arcpy.MakeFeatureLayer_management("states/continental_US.shp", "us")
basis = arcpy.mapping.Layer("us")
arcpy.mapping.AddLayer(DF, basis, "AUTO_ARRANGE")
arcpy.ApplySymbologyFromLayer_management(basis, yellow)

# Save map
mxd_city_year.saveACopy("thresh_" + city + "_" + year + ".mxd")

The code runs through (no error). However, in the resulting map document the colour still seems to be random.

What is my mistake?

  • 1
    Just a tip - in the future questions, try to post the code that can be run directly without making any modifications. In order to make your code run (apart from creating .lyr, .mxd, .shp files - which is fine), one would need to fix the city and year variables which are not declared. – Alex Tereshenkov Mar 26 '17 at 10:12
  • Yes, good point - will keep in mind for future questions. Thank you. – eigenvector Mar 26 '17 at 10:23
2

The issue is that you are applying the symbology not to the map layer, but only to a feature layer.

You need to access the newly added map layer object first using

arcpy.mapping.ListLayers(mxd_city_year, wildcard="us", data_frame=DF)[0]

and then use this map layer further in the code:

import arcpy, os

### Set directory
arcpy.env.workspace = r'C:\GIS\Temp'
arcpy.env.overwriteOutput = 1

### Define inputs
yellow = r"symbology/yellow.lyr"

# Set map document
mxd_city_year = arcpy.mapping.MapDocument(os.path.join(arcpy.env.workspace, "blank_map.mxd"))
DF = arcpy.mapping.ListDataFrames(mxd_city_year)[0]

# Add layers
arcpy.MakeFeatureLayer_management("continental_US.shp", "us")
basis = arcpy.mapping.Layer("us")
arcpy.mapping.AddLayer(DF, basis, "AUTO_ARRANGE")

#access newly added layer
map_lyr = arcpy.mapping.ListLayers(mxd_city_year, wildcard="us", data_frame=DF)[0]
arcpy.ApplySymbologyFromLayer_management(map_lyr, yellow)

# Save map
mxd_city_year.saveACopy("out.mxd")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.