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 Answer 1
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")
city
andyear
variables which are not declared.