Select to view content in your preferred language

PYTHON: My layer appears 3 times in my legend. Can't change it with arcpy but Idon't know why...

95
3
yesterday
magdatopa_ratp
Occasional Contributor

Hi everyone,

I developed a Python script to automate the generation of maps in ArcGIS Pro based on various parameters.

In my layout, I want to be able to modify the LEGEND_Item, but all my attempts have failed so far...

In fact, in my legend, I only want one layer to appear, while the others should be hidden (in the legend only).

My code does allow me to hide the layers I don’t want in the legend, but the one I do want appears 3 times in the legend. I should mention that it is inserted only once in the map. Its symbology is based on unique values, and there are 3 unique values. I suspect this is related.

Here's my code and the result:

try:
legend = "LEGENDE_" + NOMCARTE
lyt_legend = lyt.listElements("LEGEND_ELEMENT", legend)[0]
lyt_legend.title = "" # Met le titre à vide
logging.info("Titre de la légende effacé.")

except IndexError:
logging.error(f"Légende introuvable dans le layout : {legend_name}")
except Exception as e:
logging.error(f"Erreur inattendue : {str(e)}")


try:
couches_a_masquer = [DEPT_lyr.name, COMM_lyr.name, DEPT_mask_lyr.name, "COMMUNES_TRONCONS_SpatJoin"]

for item in lyt_legend.items:
if item.name in couches_a_masquer:
item.visible = False
logging.info(f"Élément de légende masqué : {item.name}")
except IndexError:
logging.error(f"Légende introuvable dans le layout : {legend}")
except Exception as e:
logging.error(f"Erreur inattendue lors de la mise à jour de la légende : {str(e)}")

 

magdatopa_ratp_0-1763564336307.png

Also want to get rid of the label "EVOL" and change the text for each value (ex. 0 should be replaced by "Unchanged value".

Any idea on how to do it if possible?

Thanks in advance

0 Kudos
3 Replies
TonyAlmeida
MVP Regular Contributor

Your symbology is unique values, so the legend automatically lists each unique value as a separate legend item. Try changing the labels for each unique value (0 → "Unchanged value", etc.), showHeading = False - Hides the layer name ("EVOL" in your case).

magdatopa_ratp
Occasional Contributor

Hi @TonyAlmeida 

Thank you for answering so fast.

That exactly what I suspected : the legend displays each unique value as a separate legend item.

I'll try changing the labels for each unique value but once it is done, do you know if  there is  a way to get a result that looks like that? (just one item displayed in the legend)

magdatopa_ratp_0-1763567001023.png

 

0 Kudos
TonyAlmeida
MVP Regular Contributor

I don't have an answer, I don't really like working with legends and python, there a pain in my opinion. 

I am sure someone will have an idea.