# Add legend with ArcPy over my interpolated map

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")


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.

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

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


#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]

#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