Skip to main content

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

Name Explanation Data 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_CORNER—Bottom left corner position

  • BOTTOM_MID_POINT—Bottom center position

  • BOTTOM_RIGHT_CORNER—Bottom right corner position

  • CENTER_POINT—Center position

  • LEFT_MID_POINT—Left center position

  • RIGHT_MID_POINT—Right center position

  • TOP_LEFT_CORNER—Top left corner position

  • TOP_MID_POINT—Top center position

  • TOP_RIGHT_CORNER—Top 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:

  • AdjustFontSize—Adjust font size.

  • AdjustColumns—Adjust columns.

  • AdjustColumnsAndFont—Adjust columns and font size.

  • AdjustFrame—Adjust frame.

  • ManualColumns—Manual 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

isOverflowing

(Read only)

Returns True if everything in the legend does not fit within the boundaries of the geometry provided. This is typically displayed with red ellipsis on a layout. The property works well within the context of a while loop. It gives you an opportunity to change the font size, fitting strategy or the size of the element until everything fits.

Boolean

locked

(Read and Write)

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

Boolean

longName

(Read only)

An element's full name including group information if it exists. For example, an element named 'Map Frame' in a group element named 'Group Element' will return a longName value of 'Group Element\\Map Frame'. If the element is not in a group, the longName will be the same as the name value.

String

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

parentGroupElement

(Read only)

If the element is in a group, the value returned will be a GroupElement, otherwise a NoneType will be returned.

GroupElement

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

Methods

addItem(layer, {add_position})

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

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.

Name Explanation Data type

layer

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

Layer

add_position

(Optional)

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

  • BOTTOM—Places the layer or layers at the bottom of the TOC layer stack.

  • TOP—Places the layer or layers at the top of the TOC layer stack.

The default value is TOP.

String

Return value

Data type Explanation

LegendItem

A LegendItem object.

applyStyleItem(style_item)

Applies a StyleItem to a LegendElement.

When referencing a StyleItem using the listStyleItems method on the ArcGISProject class, the style_class parameter must be LEGEND. For more information and code samples, refer the to StyleItem help topic.

Note:

Styles must be added to a project prior to using the applyStyleItem method. They can be added using the updateStyles method on the ArcGISProject class.

Name Explanation Data type

style_item

A reference to a StyleItem in a project.

StyleItem

getDefinition(cim_version)

Returns a legend element's CIM definition.

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

Name Explanation Data type

cim_version

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

  • V2—The 2.x version of the CIM will be used.

  • V3—The 3.x version of the CIM will be used.

String

Return value

Data type Explanation

Object

Returns the CIM definition for a LegendElement value.

moveItem(reference_item, move_item, {move_position})

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

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

Name Explanation Data 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

(Optional)

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

  • AFTER—Moves the legend item after or below the reference_item.

  • BEFORE—Moves the legend item before or above the reference_item.

The default value is BEFORE.

String

removeItem(remove_item)

Allows you to remove a legend item from a legend.

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

Name Explanation Data type

remove_item

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

LegendItem

setAnchor(anchor)

The setAnchor method controls the anchor position for a LegendElement.

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.

Name Explanation Data type

anchor

A string that specifies the location of the anchor position.

  • BOTTOM_LEFT_CORNER—The anchor will be set at the bottom left corner position.

  • BOTTOM_MID_POINT—The anchor will be set at the bottom center position.

  • BOTTOM_RIGHT_CORNER—The anchor will be set at the bottom right corner position.

  • CENTER_POINT—The anchor will be set at the center position.

  • LEFT_MID_POINT—The anchor will be set at the left center position.

  • RIGHT_MID_POINT—The anchor will be set at the right center position.

  • TOP_LEFT_CORNER—The anchor will be set at the top left corner position.

  • TOP_MID_POINT—The anchor will be set at the top center position.

  • TOP_RIGHT_CORNER—The anchor will be set at the top right corner position.

String

setDefinition(definition_object)

Sets a legend element's CIM definition.

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

Name Explanation Data type

definition_object

A modified CIM definition object originally retrieved using getDefinition.

Object

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', key='*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)