Legend not updated in exported layout (arcpy.mp exporting multiple maps)

768
3
11-08-2018 10:19 PM
KentaOkuyama
New Contributor III

Hi, 

I'm using arcpy.mp to export multiple layers at once, but having a trouble that legend is not updated.

Each layer is successfully exported as separate JPEG file by the code below. However, the legend attached to each exported output is all the same (legend of the first layer). 

I usually run my script as standalone from Jupyter notebook. When I run the code below in python window within ArcGIS pro, legend was successfully updated in each exported output.

If anybody has any idea on why it cannot be done by standalone, I would really appreciate it.

ArcGIS Pro 2.2

# This is the code I ran
aprx = arcpy.mp.ArcGISProject(r"C:\Users\kenta\Documents\ArcGIS\Projects\CoHRE_Collaboration\CoHRE_Collaboration.aprx")
maps = aprx.listMaps("Oki")[0]
layers = maps.listLayers("mean*")
layout = aprx.listLayouts("Oki_layout")[0]

for layer in layers:
   layer.visible=False
for layer in layers:
   layer.visible = True
   layout.exportToJPEG(r"C:\Users\kenta\Dropbox\Collaboration\CollaborationOki"+ "\\" + layer.name + ".JPEG")
   layer.visible = False

3 Replies
DavidMatthews3
New Contributor II

Hi Kenta,

I know this is old but did you ever resolve this issue?

Cheers

0 Kudos
SydneyWagner
New Contributor

Hello All,

I saw a couple of posts about this topic but no solution. My code makes a set of layers visible, one at a time, and exports a layout with each layer visible. I found that if I toggle the legend visibility as well, that I can get the legend to update as expected in the exported layout. To do this, I pulled the legend element (in my case, I have only one legend) from my layout object, changed the visible property to True, completed some other operations, then changed the legend visibility back to False. 

Hope this helps someone. Code below.
Sydney

# Iterate through layer objects.
for lyr in layers_to_export:
    # Make desired layer visible and make the legend visible.
    lyr.visible = True
    legend = layout.listElements("LEGEND_ELEMENT")[0]
    legend.visible = True
    
    if title_bool:
        # Change title text
        title = layout.listElements("TEXT_ELEMENT", title_element_name)[0]
        title.text = title_start + lyr.name

    # Export layout to PDF
    layout.exportToPDF(os.path.join(output_dir, f"{lyr.name}.pdf"))

    # Make layer invisible again, toggle legend off
    lyr.visible = False
    legend.visible = False

 

Mya_Yazbek
New Contributor

Hello,

 

I was having this issue with a for loop to export a series of maps. Your response with toggling legend visibility fixed my problem. Thanks! 

0 Kudos