Plot legend customization - Undocumented Matlab (2024)

8 Comments

Three years ago I explained how we can use a couple of undocumented hidden properties of the legend in order to add a legend title (the legend object had no Title property back then – this was only added in a later Matlab release, perhaps as a result of my post). Today I will expand on that article by explaining the plot legend’s internal graphics hierarchy, how we can access each of these components, and then how this information could be used to customize the separate legend components. Note that the discussion today is only relevant for HG2 legends (i.e. R2014b or newer).
Let’s start with a simple Matlab plot with a legend:

hold all;hLine1 = plot(1:5);hLine2 = plot(2:6);hLegend = legend([hLine1,hLine2], 'Location','SouthEast');hLegend.Title.String = 'MyLegend';
Plot legend customization - Undocumented Matlab (1)

This legend is composed of the following visible internal components, which can be customized separately:

Plot legend customization - Undocumented Matlab (2)


Id in screenshotAccessed viaObject typeDescriptionImportant properties
1hLegend.TitleTextTitle of the legendVisible, String, Color, FontSize, FontWeight.
2hLegend.TitleSeparatorLineStripSeparator line between title and legend entries. Only appears when title is set.Visible, LineStyle, LineWidth, ColorData (4×1 uint8)
3hLegend.BoxEdgeLineLoopBox (border) line around the entire legend (including title)Visible, LineStyle, LineWidth, ColorData (4×1 uint8)
4hLegend.EntryContainer.NodeChildren(2)LegendEntryEntry row in the legend, corresponding to hLine1Icon, Label, Object (line object in main axes)
5hLegend.EntryContainer.NodeChildren(1)LegendEntryEntry row in the legend, corresponding to hLine2Icon, Label, Object (line object in main axes)
6hLegend.EntryContainer.NodeChildren(1).LabelTextLabel of legend entryVisible, String, Color, FontSize, FontWeight
7hLegend.EntryContainer.NodeChildren(1).IconLegendIconIcon/marker of legend entryVisible, Transform.Children.Children (LineStrip object)

A pivotal object of the legend group are the LegendEntry items, one per legend row:

>> hLegendEntry = hLegend.EntryContainer.NodeChildren(1);>> get(hLegendEntry) Children: [3×1 Graphics] Color: [0 0 0] Dirty: 0 FontAngle: 'normal' FontName: 'Helvetica' FontSize: 8 FontWeight: 'normal' HandleVisibility: 'on' HitTest: 'on' Icon: [1×1 LegendIcon] Index: 0 Interpreter: 'tex' Label: [1×1 Text] LayoutInfo: [1×1 matlab.graphics.illustration.legend.ItemLayoutInfo] Legend: [1×1 Legend] Listener: [1×1 event.listener] Object: [1×1 Line] Overlay: [1×1 TriangleStrip] OverlayAlpha: 0.65 Parent: [1×1 Group] PeerVisible: 'on' PickableParts: 'visible' Selected: 'off' SelectionHighlight: 'on' Visible: 'on' VisibleListener: [1×1 event.proplistener]

Each LegendEntry contains a back-reference to the original graphics object. In my example above, hLegend.EntryContainer.NodeChildren(2).Object == hLine1, and hLegend.EntryContainer.NodeChildren(2).Object == hLine1. Note how the default legend entries order is the reverse of the order of creation of the original graphics objects. Naturally, we can modify this order by creating the legend py passing it an array of handles that is ordered differently (see the documentation of the legend function).
To get all the original graphic objects together, in a single array, we could use one of two mechanisms (note the different order of the returned objects):

% Alternative #1>> [hLegend.EntryContainer.NodeChildren.Object]'ans = 2×1 Line array: Line (data2) Line (data1)% Alternative #2>> hLegend.PlotChildrenans = 2×1 Line array: Line (data1) Line (data2)

For some reason, accessing the displayed graphic line in LegendEntry‘s Icon is not simple. For example, the LineStrip object that corresponds to hLine2 can be gotten via:

hLegendEntry = hLegend.EntryContainer.NodeChildren(1);hLegendIconLine = hLegendEntry.Icon.Transform.Children.Children; % a LineStrip object in our example

I assume that this was done to enable non-standard icons for patches and other complex objects (in which case the displayed icon would not necessarily be a LineStrip object). In the case of a line with markers, for example, hLegendIconLine would be an array of 2 objects: a LineStrip object and a separate Marker object. Still, I think that a direct reference in a hLegend.EntryContainer.NodeChildren(1).Icon property would have helped in 99% of all cases, so that we wouldn’t need to pass through the Transform object.
Anyway, once we have this object reference(s), we can modify its/their properties. In the case of a LineStrip this includes LineStyle, LineWidth, ColorData (4×1 uint8), and VertexData (which controls position/length):

>> get(hLegendIconLine(end)) % LineStrip AlignVertexCenters: 'on' AmbientStrength: 0.3 ColorBinding: 'object' ColorData: [4×1 uint8] ColorType: 'truecolor' DiffuseStrength: 0.6 HandleVisibility: 'on' HitTest: 'off' Layer: 'middle' LineCap: 'none' LineJoin: 'round' LineStyle: 'solid' LineWidth: 0.5 NormalBinding: 'none' NormalData: [] Parent: [1×1 Group] PickableParts: 'visible' SpecularColorReflectance: 1 SpecularExponent: 10 SpecularStrength: 0.9 StripData: [] Texture: [0×0 GraphicsPlaceholder] VertexData: [3×2 single] VertexIndices: [] Visible: 'on' WideLineRenderingHint: 'software'

and in the presense of markers:

>> get(hLegendIconLine(1)) % Marker EdgeColorBinding: 'object' EdgeColorData: [4×1 uint8] EdgeColorType: 'truecolor' FaceColorBinding: 'object' FaceColorData: [] FaceColorType: 'truecolor' HandleVisibility: 'on' HitTest: 'off' Layer: 'middle' LineWidth: 0.5 Parent: [1×1 Group] PickableParts: 'visible' Size: 6 SizeBinding: 'object' Style: 'circle' VertexData: [3×1 single] VertexIndices: [] Visible: 'on'

An additional undocumented legend property that is of interest is ItemTokenSize. This is a 2-element numeric array specifying the minimal size of the legend entries’ icon and label. By default hLegend.ItemTokenSize == [30,18], but we can either expand or shrink the icons/labels by setting different values. For example:

hLegend.ItemTokenSize == [10,1]; % shrink legend icons and labels

Note that regardless of the amount that we specify, the actual amount that will be used will be such that all legend labels appear.
Fun: try playing with negative values for the icon and the label and see what happens 🙂
Have you come across any other interesting undocumented aspect of Matlab legends? If so, then please share it in a comment below.

Related posts:

  1. Plot legend title Titles to plot legends are easy to achieve in HG1 (R2014a or earlier), but much more difficult in HG2 (R2014b or newer). ...
  2. Plot line transparency and color gradient Static and interpolated (gradient) colors and transparency can be set for plot lines in HG2. ...
  3. Plot markers transparency and color gradient Matlab plot-line markers can be customized to have transparency and color gradients. ...
  4. Multi-column (grid) legend This article explains how to use undocumented axes listeners for implementing multi-column plot legends...
  5. Transparent legend Matlab chart legends are opaque be default but can be made semi- or fully transparent. ...
  6. Plot LineSmoothing property LineSmoothing is a hidden and undocumented plot line property that creates anti-aliased (smooth unpixelized) lines in Matlab plots...

Handle graphics Pure Matlab Undocumented property

Print
8 Responses
  1. Plot legend customization - Undocumented Matlab (4)

    sco1Reply

    Very interesting! I never explored NodeChildren when I was building legtools and was using PlotChildren instead to do things like rearrange the legend, add/remove entries, etc.

    Have you had luck utilizing NodeChildren to perform similar options in MATLAB >= R2017a?
    R2017a introduced AutoUpdate to legend objects which broke pretty much all of the functionality I got from manipulating PlotChildren.

  2. Plot legend customization - Undocumented Matlab (5)

    Peter CookReply

    I have recently incorporated the Legend’s ItemHitFcn callback property into a utility I built.
    You can access and edit some relevant objects in the callback function, e.g.

    hLegend.ItemHitFcn = myLegendItemHitFcn(src,evnt);% The following in the callback function:evnt.Peer %access line, patch, image, GraphPlot, etc... evnt.Item.Label %access text object for that legend entrysrc.String{evnt.Item.Index} = 'new string'; %edit the legend entry name
  • Plot legend customization - Undocumented Matlab (6)

    Yair AltmanReply

    @Peter – while the legend object’s ItemHitFcn callback property is documented/supported, the Item property of the eventData object (which is passed to the callback function in run-time when you click a legend entry) is indeed hidden/undocumented. This eventData.Item property contains the LegendEntry item that was clicked. Thanks for pointing it out.

  • Plot legend customization - Undocumented Matlab (7)

    AaronReply

    It would appear that if you’re using these properties in a function or loop it is important to call drawnow before attempting to utilise any of the LegendEntry objects, otherwise they will not exist yet and you will get errors.

  • Plot legend customization - Undocumented Matlab (8)

    PraveenReply

    Hi That’s alright, how do I set for example, marker size in the legend, when I try to set it: hLegend.EntryContainer.NodeChildren(1).Icon.Transform.Children.Children.Size = 15; I get an error saying I can’t set readonly properties, any tips how to go about that. Thanks

    • Plot legend customization - Undocumented Matlab (9)

      Yair AltmanReply

      @Praveen – first note that you have to call drawnow before accessing any of the internal legend components. In addition, note that hLegend.EntryContainer.NodeChildren(1).Icon.Transform.Children.Children returns an array of objects (Marker and LineStrip) and you can only set the Size property of the Marker, not the LineStrip (duh). Here’s a working example:

      figure; hold all;hLine1 = plot(1:5,'o-b'); hLine2 = plot(2:6,'-sr');hLegend = legend([hLine1,hLine2], 'Location','SouthEast');hLegend.Title.String = 'MyLegend';drawnow;hLegend.EntryContainer.NodeChildren(1).Icon.Transform.Children.Children(1).Size = 15;
  • Plot legend customization - Undocumented Matlab (10)

    DevReply

    Same question as sco1: Have you had luck utilizing NodeChildren to perform similar options in MATLAB >= R2017a?

  • Plot legend customization - Undocumented Matlab (11)

    GresReply

    In 2018b, you can get the icons by calling [hh,icons,plots,txt] = legend({‘Line 1’});

  • Leave a Reply
    HTML tags such as <b> or <i> are accepted.
    Wrap code fragments inside <pre lang="matlab"> tags, like this:
    <pre lang="matlab">
    a = magic(3);
    disp(sum(a))
    </pre>
    I reserve the right to edit/delete comments (read the site policies).
    Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.
    Plot legend customization - Undocumented Matlab (2024)

    FAQs

    How do you change the transparency of the legend in MATLAB? ›

    You can use PatchInLegend = findobj(BL, 'type', 'patch'); to find the patch objects in your legend. You can then set their transparency using set(PatchInLegend, 'facea', 0.5) to set their transparency. So the colour changes, and it does look a lot better.

    How to manipulate legend in MATLAB? ›

    You can change different aspects of a legend by setting properties. You can set properties by specifying name-value arguments when you call legend , or you can set properties of the Legend object after you call legend .

    How to disable legend MATLAB? ›

    Below are two ways to remove a legend from a plot:
    1. Use the "findobj" function to find the legend(s) and the "delete" function to delete them: % Find and delete the legend. lgd = findobj('type', 'legend') ...
    2. If you do not want to delete the legend, you can turn off the legend's visibility: set(lgd(idx), 'visible', 'off')
    Mar 26, 2016

    How do I enable legend in MATLAB? ›

    To add a legend title, set the String property of the legend text object. To change the title appearance, such as the font style or color, set legend text properties. For a list, see Text Properties. plot(rand(3)); lgd = legend('line 1','line 2','line 3'); lgd.

    How do I make my legend background transparent? ›

    You can set legend. bgcolor to an RGBA value e.g. 'rgba(0,0,0,0)' will make the legend fully transparent.

    How do I change the transparency of a plot in MATLAB? ›

    alpha value sets the face transparency for objects in the current axes that support transparency. Specify value as 'clear' or 'opaque' , or as a number in the range [0, 1]. A value of 0 makes the objects transparent, and value of 1 makes the objects fully opaque.

    How to make custom legends in MATLAB? ›

    Set the DisplayName property as a name-value pair when calling the plotting functions. Then, call the legend command to create the legend. Legends automatically update when you add or delete a data series. If you add more data to the axes, use the DisplayName property to specify the labels.

    How do I prevent the legend from updating in MATLAB? ›

    The legend has been changed so that by default it updates when data is added to or removed from a plot automatically. To prevent this behavior, set the legends "AutoUpdate" property. The above line can also be added to the MATLAB startup script if the user wants it to apply it to every MATLAB session.

    How to control legend size MATLAB? ›

    You can change the font size for a MATLAB legend by setting the 'FontSize' property of the Legend object. For example, plot four lines. Create a legend and assign the Legend object to the variable 'lgd'. Then, use dot notation to access the 'FontSize' property and set the value to 14 points.

    How do I not show data in legend in MATLAB? ›

    1- Select the curve you don't want have legend. 2- Go to the "more properties" (while the curve is still selected). 3- Turn "HandleVisibility" off.

    What is the limit of legend in MATLAB? ›

    Accepted Answer

    Legends are currently limited to no more than 50 entries. Usually in plots with more than 50 features, the plot is so cluttered and the legend is so large that it is more advisable to select just a few key items to display in the legend.

    Why do we use legend in MATLAB? ›

    legend associates strings with the objects in the Axes in the same order that they are listed in the Axes Children property. By default, the legend annotates the current Axes. MATLAB displays only one legend per Axes. legend positions the legend based on a variety of factors, such as what objects the legend obscures.

    Why is MATLAB ignoring extra legend entries? ›

    The warning "Ignoring extra legend entries" happens if you call legend() with more names than there are lines in your axes. In this case, it is related to your use of "hold on".

    How do you add a legend to a plot in MATLAB Python? ›

    Matplotlib.pyplot.legend() in Python

    The attribute Loc in legend() is used to specify the location of the legend. The default value of loc is loc= “best” (upper left). The strings 'upper left', 'upper right', 'lower left', and 'lower right' place the legend at the corresponding corner of the axes/figure.

    How do I change the transparency in Matplotlib? ›

    Matplotlib allows you to regulate the transparency of a graph plot using the alpha attribute. By default, alpha=1. If you would like to form the graph plot more transparent, then you'll make alpha but 1, such as 0.5 or 0.25.

    How do I change the opacity of an image in MATLAB? ›

    Use the alpha function to set the transparency for all image, patch, and surface objects in the current axes. Specify a transparency value between 0 (fully transparent) and 1 (fully opaque).

    How do you make a figure background transparent in MATLAB? ›

    Direct link to this answer
    1. x = 0:.1:2*pi;
    2. y = sin(x);
    3. % save to transparented image.
    4. figure;
    5. plot(x,y,'LineWidth',4);
    6. set(gcf, 'color', 'none');
    7. set(gca, 'color', 'none');
    8. exportgraphics(gcf,'transparent.eps',... % since R2020a.
    Mar 2, 2018

    How can you change the transparency of an object? ›

    Select the object you want to modify in the Scene View. Click Item Tools tab Appearance panel. Move the Transparency slider to adjust how transparent or opaque the selected object is.

    Top Articles
    Latest Posts
    Article information

    Author: Laurine Ryan

    Last Updated:

    Views: 5589

    Rating: 4.7 / 5 (77 voted)

    Reviews: 84% of readers found this page helpful

    Author information

    Name: Laurine Ryan

    Birthday: 1994-12-23

    Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

    Phone: +2366831109631

    Job: Sales Producer

    Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

    Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.