LegendElement

Summary

The LegendElement class provides access to properties and methods for managing legend elements on a layout.

Discussion

A LegendElement object is a specific type of MapSurroundElement layout element. It also has an association with a MapFrame object, but it has additional properties specific to legends, including access to LegendItem objects. The listElements method on the Layout object returns a Python list of page layout element objects. To return a list of LegendElement objects only, use the LEGEND_ELEMENT constant for the element_type parameter. A wildcard value can also be used to further refine the search based on the element's name value. Give each page layout element a unique name so it can be easily referenced.

You can create legends using the createMapSurroundElement method on the Layout object with map_surround_type set to LEGEND.You can specify an existing StyleItem value during creation to control how the element appears in the layout.

By default, layers added to a Map object are automatically added to a LegendElement object. This allows you to create a layout with an empty map and legend but have those items dynamically update when new layers are added to the map. There are several properties that start with 'sync' that allow you to control how items are added to a legend. You can also use the fittingStrategy and columnCount properties to control the appearance of the legend.

The elementPositionX and elementPositionY values are based on the element's anchor position, which is set on the Format tab. If you want a LegendElement object to grow downward when layers are added, set the anchor position to the upper left. You can change the position using the setAnchor method.

The items property will return a list of LegendItem classes that can be individually modified to further customize the contents of a legend. The LegendElement class also provides AddItem, MoveItem, and RemoveItem methods that allow you to manage the items in a legend. Both the LegendElement and the LegendItem classes only provide access to common properties. Finer-grained access can be accomplished using Python CIM access.

Properties

PropertyExplanationData Type
anchor
(Read Only)

Returns one of the following string values that represent the current anchor position. To change the value, use the setAnchor method.

  • BOTTOM_LEFT_CORNERBottom left corner position
  • BOTTOM_MID_POINTBottom center position
  • BOTTOM_RIGHT_CORNERBottom right corner position
  • CENTER_POINTCenter position
  • LEFT_MID_POINTLeft center position
  • RIGHT_MID_POINTRight center position
  • TOP_LEFT_CORNERTop left corner position
  • TOP_MID_POINTTop center position
  • TOP_RIGHT_CORNERTop right corner position
String
columnCount
(Read and Write)

The number of specified columns in a legend. This property only applies if the fittingStrategy is set to AdjustFontSize, AdjustFrame, or ManualColumns.

Long
elementHeight
(Read and Write)

The height of the element in page units.

Double
elementPositionX
(Read and Write)

The x-location of the element's anchor position. The units assigned or reported are in page units.

Double
elementPositionY
(Read and Write)

The y-location of the element's anchor position. The units assigned or reported are in page units.

Double
elementRotation
(Read and Write)

Rotates the element relative to the anchor position. Positive values are counterclockwise and negative values are clockwise.

Double
elementWidth
(Read and Write)

The width of the element in page units.

Double
fittingStrategy
(Read and Write)

A string that represents a valid fitting strategy method. The valid values are as follows:

  • AdjustFontSizeAdjust font size.
  • AdjustColumnsAdjust columns.
  • AdjustColumnsAndFontAdjust columns and font size.
  • AdjustFrameAdjust frame.
  • ManualColumnsManual columns.
String
items
(Read Only)

Returns a list of the associated LegendItem classes. You cannot directly set this property, but you can iterate through the legend items and modify their properties.

List
locked
(Read and Write)

When set to True, the element cannot be graphically selected in the layout view.

Boolean
mapFrame
(Read and Write)

A reference to the associated MapFrame.

MapFrame
name
(Read and Write)

The name of the element. It is important that all elements have a unique name so they can be easily referenced.

String
showTitle
(Read and Write)

A Boolean that controls whether the title is displayed in the legend.

Boolean
syncLayerOrder
(Read and Write)

A Boolean that controls whether the items in the legend are in the same order as the layers in the map.

Boolean
syncLayerVisibility
(Read and Write)

A Boolean that controls whether an item should automatically appear in the legend if it is visible in the map.

Boolean
syncNewLayer
(Read and Write)

A Boolean that controls whether an item should automatically be added to the legend when added to the map.

Boolean
syncReferenceScale
(Read and Write)

A Boolean that controls whether the symbols in the legend should match the scaling of the symbols in a map if a reference scale is set.

Boolean
title
(Read and Write)

The text string that represents the legend's title.

String
type
(Read Only)

Returns a value of LEGEND_ELEMENT.

String
visible
(Read and Write)

Returns True if the element is visible on the layout. Rather than having to move unwanted objects off the page before printing or exporting, you can turn the element's visibility on and off.

Boolean

Method Overview

MethodExplanation
addItem (layer, {add_position})

Allows you to add a Layer to a legend using basic placement options.

getDefinition (cim_version)

Returns a legend element's CIM definition.

moveItem (reference_item, move_item, {move_position})

Allows you to move a legend item to a specific location within a legend.

removeItem (remove_item)

Allows you to remove a legend item from a legend.

setAnchor (anchor)

The setAnchor method controls the anchor position for a LegendElement.

setDefinition (definition_object)

Sets a legend element's CIM definition.

Methods

addItem (layer, {add_position})
ParameterExplanationData Type
layer

A reference to a Layer object representing the layer to be added to a legend as a LegendItem.

Layer
add_position

A constant that determines the placement of the added layer within the legend.

  • BOTTOMPlaces the layer or layers at the bottom of the TOC layer stack.
  • TOPPlaces the layer or layers at the top of the TOC layer stack.

(The default value is TOP)

String
Return Value
Data TypeExplanation
LegendItem

A LegendItem object.

The addItem method allows you to add a layer to a legend on a layout. The default add_position adds the layer to the top of the list of legend items, therefore appears first. For more precise legend item placement, refer to the moveItem method.

getDefinition (cim_version)
ParameterExplanationData Type
cim_version

A string that represents the major version of the CIM that will be used.

  • V2The 2.x version of the CIM will be used.
  • V3The 3.x version of the CIM will be used.
String
Return Value
Data TypeExplanation
Object

Returns the CIM definition for a LegendElement value.

For more information about working with the CIM and samples, see Python CIM access.

moveItem (reference_item, move_item, {move_position})
ParameterExplanationData Type
reference_item

A LegendItem object representing an existing legend item that determines the relative location where the move_item will be moved.

LegendItem
move_item

A reference to a LegendItem object representing the layer to be moved.

Layer
move_position

A constant that determines the placement of the moved layer relative to the reference layer.

  • AFTERMoves the legend item after or below the reference_item.
  • BEFOREMoves the legend item before or above the reference_item.

(The default value is BEFORE)

String

The moveItem method moves a legend item in a legend. The move_item can be moved either AFTER or BEFORE the reference_item.

removeItem (remove_item)
ParameterExplanationData Type
remove_item

A reference to a LegendItem object representing the item to be removed.

LegendItem

The removeItem method removes a single legend item from a legend.

setAnchor (anchor)
ParameterExplanationData Type
anchor

A string that specifies the location of the anchor position.

  • BOTTOM_LEFT_CORNERThe anchor will be set at the bottom left corner position.
  • BOTTOM_MID_POINTThe anchor will be set at the bottom center position.
  • BOTTOM_RIGHT_CORNERThe anchor will be set at the bottom right corner position.
  • CENTER_POINTThe anchor will be set at the center position.
  • LEFT_MID_POINTThe anchor will be set at the left center position.
  • RIGHT_MID_POINTThe anchor will be set at the right center position.
  • TOP_LEFT_CORNERThe anchor will be set at the top left corner position.
  • TOP_MID_POINTThe anchor will be set at the top center position.
  • TOP_RIGHT_CORNERThe anchor will be set at the top right corner position.
String

Setting the anchor position is helpful because you can control how the element might expand when resized. For example, the default anchor position for a legend element is TOP_LEFT_CORNER. If you change the anchor location to BOTTOM_RIGHT_CORNER, changing elementHeight will expand the element downward, and changing elementWidth will expand the element to the left.

setDefinition (definition_object)
ParameterExplanationData Type
definition_object

A modified CIM definition object originally retrieved using getDefinition.

Object

For more information about working with the CIM and samples, see Python CIM access.

Code sample

LegendElement example 1

The following script adds a new legend to a layout and updates several properties. Before adding a layer file, it turns off layer synchronization so the terrain color map does not appear. After the layer is added, layer synchronization is turned back on.

import arcpy
p = arcpy.mp.ArcGISProject(r'C:\Projects\YosemiteNP\Yosemite_Trails.aprx')

#Create a new legend and set legend properties
lyt = p.listLayouts('Main Attractions')[0]
mf = lyt.listElements('MapFrame_Element', 'Yose*')[0]
legSi = p.listStyleItems('ArcGIS 2D', 'LEGEND', 'Legend 3' )[0]
leg = lyt.createMapSurroundElement(arcpy.Point(0.75,3.5), 'LEGEND', mf, legSi, 'New Legend Element')
leg.elementWidth = 7
leg.elementHeight = 3
leg.fittingStrategy = 'AdjustFontSize'
leg.columnCount = 5
leg.title = 'Yosemite National Park'

#Add a layer file but first turn of legend layer synchronization
leg.syncNewLayer = False
lyr = arcpy.mp.LayerFile(r'C:\Projects\YosemiteNP\LayerFiles\Terrain.lyrx')
m = p.listMaps('Yosemite National Park')[0]
m.addLayer(lyr, 'BOTTOM')
leg.syncNewLayer = True 
p.saveACopy(r"C:\Projects\YosemiteNP\Yosemite_Trails_OUT.aprx")
LegendElement example 2

The following script sets fittingStrategy to ManualColumns and sets columnCount to 4. Next, the script builds a dictionary that includes the legend item name and the columns it will be placed into. Finally, the script iterates through each legend item and places them in the appropriate column based on the dictionary values.

import arcpy, os, sys
relpath = os.path.dirname(sys.argv[0])

p = arcpy.mp.ArcGISProject(os.path.join(relpath, 'NewMexicoGeology', 'NewMexicoGeology.aprx'))
lyt = p.listLayouts('Layout')[0]
leg = lyt.listElements('LEGEND_ELEMENT')[0]

#Change Title and fitting strategy to (4) Manual Columns
leg.fittingStrategy = 'ManualColumns'
leg.columnCount = 4

#Dictionary of item name and column pairs
legDict = {'Cretaceous' :    1,
           'Mississippian' : 1,
           'Tertiary' :      2,
           'Silurian' :      2,
           'Ordovician' :    2,
           'Quaternary' :    3,
           'Jurassic' :      3,
           'Devonian' :      3,
           'Permian':        4,
           'Proterozoic' :   4,
           'Other' :         4 }

#Place each legend item into the appropriate column based on name
for legItm in leg.items:
  legItm.column = legDict[legItm.name]

p.saveACopy(os.path.join(relpath, 'NewMexicoGeology', 'NewMexicoGeology_OUT.aprx'))
LegendElement example 3

The following script uses Python CIM access to modify the legend's title symbology and patch width. It also uses the CIM to modify the patch shape for each class in a unique value renderer.

p = arcpy.mp.ArcGISProject('current')
lyt = p.listLayouts('Layout')[0]
leg = lyt.listElements('LEGEND_ELEMENT')[0]

#Use Legend poperties to display and modify title text
leg.showTitle = True
leg.title = "Legend CIM Changes"

#CIM modifications to Title font properties and patch width
lyt_cim = lyt.getDefinition('V3')
for elm in lyt_cim.elements:
  if elm.name == "Legend":
    leg_cim = lyt_cim.elements[1]
    leg_cim.titleSymbol.symbol.height = 30
    leg_cim.titleSymbol.symbol.horizontalAlignment = 'Center'
    leg_cim.titleSymbol.symbol.fontStyleName = 'Bold'
    leg_cim.titleSymbol.symbol.symbol.symbolLayers[0].color.values = [255,0,0,100]
    for itm in reversed(elm.items):       #Done in reversed order
      itm.patchWidth = 50
lyt.setDefinition(lyt_cim)

#CIM modification to layer patch shape (it affects legend items)
m = p.listMaps('Overview Map')[0]
for itm in leg.items:
  lyr = m.listLayers(itm.name)[0]
  if lyr.symbology.renderer.type == 'UniqueValueRenderer':
    lyr_cim = lyr.getDefinition('V3')
    for grp in lyr_cim.renderer.groups:   #Iterate through each group
      for cls in grp.classes:             #Iterate through each class
        cls.patch = "AreaNaturalPoly"     #Called Natural area in app
  lyr.setDefinition(lyr_cim)