1

I have created an interpolated map with arcpy.IDW_ga and I am exporting it to PDF with arcpy.mapping.ExportToPDF. How can I add a legend to the map with ArcPy? In the end, I want to apply the code to create 100 maps, so manually is not a solution. I know I can just go to Insert>> Legend, but I need an automated solution.

arcpy.IDW_ga(in_features = in_features, 
             z_field= z_field, out_ga_layer="", 
             out_raster="Interpolation/year/" + name_save, 
             cell_size="6.46298456489016E-03", 
             power="2", 
             search_neighborhood="NBRTYPE=Standard S_MAJOR=0.336780807796406 S_MINOR=0.336780807796406 ANGLE=0 NBR_MAX=15 NBR_MIN=10 SECTOR_TYPE=ONE_SECTOR", 
             weight_field="")

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]  
arcpy.mapping.ExportToPDF(mxd,  "C:/Users/"mypdf.pdf")

1 Answer 1

3

Create/save the map document with a legend. When you add your layer it will automatically be added to the legend as long as Add a new item to the legend when a new layer is added to the map is selected.

enter image description here

You can 'click this box' via arcpy as well.

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

Full code to add your raster result:

#get mxd object
mxd = arcpy.mapping.MapDocument (r"path\to\your\mxd.mxd")
#get data frame
df = arcpy.mapping.ListDataFrames (mxd) [0]

#get legend
legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")[0]
#add new items to legend
legend.autoAdd = True

#IDW
arcpy.IDW_ga(in_features = in_features, 
             z_field= z_field, out_ga_layer="", 
             out_raster="Interpolation/year/" + name_save, 
             cell_size="6.46298456489016E-03", 
             power="2", 
             search_neighborhood="NBRTYPE=Standard S_MAJOR=0.336780807796406 S_MINOR=0.336780807796406 ANGLE=0 NBR_MAX=15 NBR_MIN=10 SECTOR_TYPE=ONE_SECTOR", 
             weight_field="")
#create raster layer
rastLyr = arcpy.MakeRasterLayer_management("Interpolation/year/" + name_save, 'rast') [0]
#add raster layer - it will be added to the legend as well
arcpy.mapping.AddLayer (df, rastLyr)
1
  • Thank you! It works
    – IceBelt
    Commented Nov 5, 2019 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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