Does anyone know why my legend is doing this?
lyt = p.listLayouts('Layout')[0]
mf = lyt.listElements('MAPFRAME_ELEMENT', 'New Map Frame')[0] # Ensure you reference the correct map frame
# Define legend position and dimensions
legend_x = 6
legend_y = 1.3
legend_width = 12 # Legend width
legend_height = 5 # Legend height
# Define the legend style
legend_style = p.listStyleItems('ArcGIS 2D', 'LEGEND', 'Legend 1')[0]
# Create the legend
legend = lyt.createMapSurroundElement(
arcpy.Point(legend_x, legend_y), 'LEGEND', mf, legend_style, 'Map Legend'
)
# Configure legend appearance and behavior
legend.elementWidth = legend_width
legend.elementHeight = legend_height
legend.fittingStrategy = 'ManualColumns' # Prevents auto-grouping
legend.columnCount = 2 # Arrange items in two columns
legend.showTitle = False # Hide the legend title
# Use CIM to refine the legend further
lyt_cim = lyt.getDefinition('V3')
for elm in lyt_cim.elements:
if elm.name == "Map Legend": # Replace "Map Legend" with the actual legend name
# Access the legend CIM definition
legend_cim = elm
# Remove the background frame/outline by setting the frame to None
legend_cim.frame = None
# Hide subheaders and duplicate category names
for item in legend_cim.items:
item.showHeading = False # Remove subheaders
item.showLabels = False # Hide duplicate category names
# Update the definition back to the layout
lyt.setDefinition(lyt_cim)
# Filter legend items to display only relevant categories on the map
valid_categories_in_map = [
"Damage or destruction, looting, or theft of cultural heritage",
"Damage or destruction of civilian critical infrastructure",
"Enslavement",
"Extrajudicial killing",
"Forced disappearance",
"Gender-based or other conflict-related sexual violence",
"Human trafficking",
"Indiscriminate use of weapons",
"Kidnapping",
"Mass execution",
"Military operations (battle, shelling)",
"Movement of military, paramilitary, or other troops and equipment",
"Persecution based on political, racial, ethnic, gender, or sexual orientation",
"Torture or indications of torture",
"Unlawful detention",
"Violent crackdowns on protesters/opponents/civil rights abuse",
"Willful killing of civilians"
]
# Filter and remove items not relevant to the map
for item in legend.items:
if item.name not in valid_categories_in_map:
legend.removeItem(item)
It seems to be cutting off the text in my legend element. I attached a photo of what I am encountering.
Maybe add a third column, adjust font size and maybe increase the legend_width. Also, check spacing between legend items (patchHeight and pathWidth.)