Plot legend title - Undocumented Matlab (2024)

11 Comments

This blog post was supposed to be a piece of cake: The problem description was that we wish to display a text title next to the legend box in plot axes. Sounds simple enough. After all, in HG1 (R2014a and earlier), a legend was a simple wrapper around a standard Matlab axes. Therefore, we can simply access the legend axes’s title handle, and modify its properties. This works very well in HG1:

hold all;hLine1 = plot(1:5);hLine2 = plot(2:6);hLegend = legend([hLine1,hLine2], 'Location','NorthWest');hTitle = get(hLegend,'title');set(hTitle, 'String','Plot types:', 'VerticalAlignment','middle', 'FontSize',8);
Plot legend title - Undocumented Matlab (1)

HG2

How hard then could a corresponding solution be in HG2 (R2014b+), right?
Well, it turns out that hard enough (at least for me)…

In this blog I’ve presented ~300 posts so far that discuss solutions to problems. Readers of this blog always hear the success stories, and might mistakenly think that every problem has a similarly simple solution that can be hacked away in a few lines of nifty code.
Well, the truth must be told that for each investigation that yields such a success story, there is at least one other investigation in which I failed to find a solution, no matter how hard I tried or countless hours spent digging (this is not to say that the success stories are easy – distilling a solution to a few lines of code often takes hours of research). In any case, maybe some of these problems for which I have not found a solution do have one that I have simply not discovered, and maybe they don’t – in most likelihood I will never know.
This is yet another example of such a spectacular failure on my part. Try as I may in HG2, I could find no internal handle anywhere to the legend’s axes or title handle. As far as I could tell, HG2’s legend is a standalone object of class matlab.graphics.illustration.Legend that derives from exactly the same superclasses as axes:

>> sort(superclasses('matlab.graphics.axis.Axes'))ans = 'JavaVisible' 'dynamicprops' 'handle' 'matlab.graphics.Graphics' 'matlab.graphics.GraphicsDisplay' 'matlab.graphics.internal.GraphicsJavaVisible' 'matlab.mixin.CustomDisplay' 'matlab.mixin.Heterogeneous' 'matlab.mixin.SetGet'
>> sort(superclasses('matlab.graphics.illustration.Legend'))ans = 'JavaVisible' 'dynamicprops' 'handle' 'matlab.graphics.Graphics' 'matlab.graphics.GraphicsDisplay' 'matlab.graphics.internal.GraphicsJavaVisible' 'matlab.mixin.CustomDisplay' 'matlab.mixin.Heterogeneous' 'matlab.mixin.SetGet'

This make sense, since they share many properties/features. But it also means that legends are apparently not axes but rather unrelated siblings. As such, if MathWorks chose to remove the Title property from the legend object, we will never find it.

So what can we do in HG2?

Well, we can always resort to the poor-man’s solution of an optical illusion: displaying a an invisible axes object having the same Position as the legend box, with an axes title. We attach property listeners on the legend’s Units, Position and Visible properties, linking them to the corresponding axes properties, so that the title will change if and when the legend’s properties change (for example, by dragging the legend to a different location, or by resizing the figure). We also add an event listener to destroy the axes (and its title) when the legend is destroyed:

% Create the legendhLegend = legend(...); % as before% Create an invisible axes at the same position as the legendhLegendAxes = axes('Parent',hLegend.Parent, 'Units',hLegend.Units, 'Position',hLegend.Position, ... 'XTick',[] ,'YTick',[], 'Color','none', 'YColor','none', 'XColor','none', 'HandleVisibility','off', 'HitTest','off');% Add the axes title (will appear directly above the legend box)hTitle = title(hLegendAxes, 'Plot types:', 'FontWeight','normal', 'FontSize',8); % Default is bold-11, which is too large% Link between some property values of the legend and the new axeshLinks = linkprop([hLegend,hLegendAxes], {'Units', 'Position', 'Visible'});% persist hLinks, otherwise they will stop working when they go out of scopesetappdata(hLegendAxes, 'listeners', hLinks);% Add destruction event listener (no need to persist here - this is done by addlistener)addlistener(hLegend, 'ObjectBeingDestroyed', @(h,e)delete(hLegendAxes));
Plot legend title - Undocumented Matlab (2)

Yes, this is indeed a bit of an unfortunate regression from HG1, but I currently see no other way to solve this. We can’t win ’em all… If you know a better solution, I’m all ears. Please shoot me an email, or leave a comment below.
Update: As suggested below by Martin, here is a more elegant solution, which attaches a text object as a direct child of the legend’s hidden property DecorationContainer (we cannot add it as a child of the legend since this is prevented and results in an error):

hLegend = legend(...);hlt = text(... 'Parent', hLegend.DecorationContainer, ... 'String', 'Title', ... 'HorizontalAlignment', 'center', ... 'VerticalAlignment', 'bottom', ... 'Position', [0.5, 1.05, 0], ... 'Units', 'normalized');

The title appears to stay attached to the legend and the Parent property of the text object even reports the legend object as its parent:

hLegend.Location = 'southwest'; % Test the title's attachmenthlt.Parent % Returns hLegend

– thanks Martin!
Happy Passover/Easter everybody!
Addendum: As pointed out by Eike in a comment below, Matlab release R2016a has restored the Title property. This property holds a handle to a Text object, for which we can set properties such as String, Color, FontSize etc.

Related posts:

  1. Plot legend customization Matlab plot legends and their internal components can be customized using a variety of undocumented properties that are easily accessible. ...
  2. Bug and workaround in timeseries plot Matlab's internal hgconvertunits function has a bug that affects timeseries plots. Luckily there is a simple workaround....
  3. Transparent legend Matlab chart legends are opaque be default but can be made semi- or fully transparent. ...
  4. Multi-column (grid) legend This article explains how to use undocumented axes listeners for implementing multi-column plot legends...
  5. Bar plot customizations Matlab bar charts can be customized in various nifty ways. ...
  6. Plot LimInclude properties The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....

Handle graphics HG2 Optical illusion Pure Matlab Undocumented feature

Print
11 Responses
  1. Plot legend title - Undocumented Matlab (4)

    FredReply

    The workaround I use is to plot the first point of my first line with ‘w.’, then include it as the first handle in my call to legend, with its text as the desired legend title. In this example the handles for the legend are left implicit.

    figurehold on;plot(r(1),'w.');plot(r);legend('Traces','First','Second')

    Cheers,

  2. Plot legend title - Undocumented Matlab (5)

    MartinReply

    I haven’t really tested for any undesired side effects, but I have the feeling that this qualifies as a more elegant solution:

    hLegend = legend(...)hlt = text(... 'Parent', hLegend.DecorationContainer, ... 'String', 'Title', ... 'HorizontalAlignment', 'center', ... 'VerticalAlignment', 'bottom', ... 'Position', [0.5, 1.05, 0], ... 'Units', 'normalized');

    The title appears to stay attached to the legend and the Parent property of the text object even reports the legend object as its parent:

    hLegend.Location = 'southwest'; % Test the title's attachmenthlt.Parent % Returns hLegend

    I tested this with R2015a. The DecorationContainer was simply the first in a rather long list of properties that sounded like it could be useful.

  • Plot legend title - Undocumented Matlab (6)

    Yair AltmanReply

    @Martin – thanks! this is indeed more elegant. I tried setting a text object’s Parent directly to the legend and received an error (“Text cannot be a child of Legend”); I then tried to set the DecorationContainer’s title property and got another error (since it’s not an axes and has no such property); but I didn’t think to simply try what you did, which is a variant of my failed attempts…

    I guess it shows us that we should never give up hope, maybe just take a step back and rethink about the problem.

    Thanks again!

  • Plot legend title - Undocumented Matlab (7)

    MartinReply

    @Yair – thanks for improving my comment and fixing the minor error I included! I see you read those comments very carefully. 🙂

    R2015a made it easier to to explore HG2 (and the many undocumented properties/methods of the related classes) by adding the new (and hidden) Type property to the meta.property class and the InputTypes and OutputTypes properties to the the meta.method class. For example:

    mc = ?matlab.graphics.axis.Axes;mc.PropertyList(1).Name % Cameramc.PropertyList(1).Type % matlab.graphics.axis.camera.Cameramc.MethodList(49).Name % addlistenermc.MethodList(49).InputNames % [sources, propertyname, eventname, callback]mc.MethodList(49).InputTypes % [handle, asciiString, char vector, function_handle scalar]

    Knowing the type of a property can be especially helpful to find out what can be assigned to it. Sometimes one even gets a list of valid values (e.g. the CameraMode property of the above Axes class).

    • Plot legend title - Undocumented Matlab (8)

      Yair Altman

      @Martin – thanks, interesting. I have a hunch that this is related to the undocumented mechanism of setting class-property types using the so-called “@-filter”:

      properties Name@char = 'abc' Width@double = 10end

      Unfortunately, I tried this @-filter on method input/output args and it croacks. So either it’s not implemented yet, or MathWorks may have changed the syntax, or maybe I’m just misreading the situation…

  • Plot legend title - Undocumented Matlab (9)

    MartinReply

    @Yair – Yes, I’d say this is related. Obviously, there is internal support for data types for both properties and function/method arguments. But only the former got the (undocumented) @-syntax in the MATLAB language, as described by your linked post. The latter seems to be reserved to built-in functions and methods of built-in classes, that are implemented in C++ and are thus not restricted by what is exposed to the MATLAB language. (I also tried and failed to find a syntax that would work for arguments.)

    I wonder why MathWorks decided to expose only “half” of this data type feature to MATLAB programmers. And I wonder why they added “full” support for querying this information directly from MATLAB in R2015a. (Not that I’m complaining, it provides interesting insights.)

    Finally, I wonder what those data types really are. (I think we had something similar in the UDD class system.) They are not real classes, as can be seen in many instances in HG2. But classes can be used as data types. Will data types be fully exposed to the MATLAB language? Will we be able to create and use custom data types in the future?

  • Plot legend title - Undocumented Matlab (10)

    Robert CummingReply

    @Yair,

    Interesting as always – Adding a legend title is one of the functions in my GUI Toolbox and I uploaded this particular code as a FEX submission which covers HG1 & HG2.

    @Martin – Nice solution! 🙂

  • Plot legend title - Undocumented Matlab (11)

    Tom HeineReply

    I have found one downside to the Martin’s approach. For some reason, when I save the figure as a .fig, the legend title isn’t saved.

  • Plot legend title - Undocumented Matlab (12)

    Eike BlechschmidtReply

    In Matlab 2016a it works if you use:

    hLegend = legend();hLegend.Title.String = 'My Legend Title'.
  • Plot legend title - Undocumented Matlab (13)

    EBHReply

    You might want to see another issue with the new legend title that I solved here

    • Plot legend title - Undocumented Matlab (14)

      Yair AltmanReply

      ???

    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 title - Undocumented Matlab (2024)

    FAQs

    Can you title a 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 you specify a legend in a plot in MATLAB? ›

    Alternatively, you can specify the legend labels using the DisplayName property. 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.

    How do I hide the legend entry in MATLAB plot? ›

    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

    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".

    Does a legend need a title? ›

    Legend titles should be used to add context and explain your map. Don't title your legend “legend”—your reader will know it is a legend. If there's no better title then "legend", it doesn't need a title at all. If your map does require a legend, use the same care to design it as you do with map symbols and labels.

    How do you give a legend title? ›

    Direct link to this question
    1. x = 1:0.1:10;
    2. y = sin(x);
    3. subplot 211.
    4. plot(x,y)
    5. [leg,att] = legend('show');
    6. title(leg,'my title')
    7. leg.Title.Visible = 'on';
    8. subplot 212.
    Feb 13, 2017

    How to give plot title in MATLAB? ›

    Create a plot. Then create a title and a subtitle by calling the title function with two character vectors as arguments. Use the 'Color' name-value pair argument to customize the color for both lines of text. Specify two return arguments to store the text objects for the title and subtitle.

    How do you put a legend inside a plot? ›

    You can place the legend literally anywhere. To put it around the chart, use the legend.position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

    What is plot legend ()? ›

    legend() A legend is used to describe elements for a particular area of a graph. Python has a function called legend() which is used to place a legend on the axis. The legend function has an attribute called loc which is used to denote the location of the legend.

    How do I hide the legend and title of a chart? ›

    Click Format to open the chart formatting options. In the Chart pane, expand the Legend section. Add or edit the Legend to meet your needs. Use the switch to show or hide the legend.

    How do I not show the 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.

    How do I stop MATLAB from adding legend entries? ›

    Accepted Answer

    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 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 do you suppress legend output in MATLAB? ›

    One can suppress a legend entry for a line object h by executing h. HandleVisibility='off' or h. Annotation. LegendInformation.

    Can you have two legends in MATLAB? ›

    As far as I know, you can only have one legend-window for one set of axes in MATLAB, so the idea is: add a second (exatly equal) set of axes to the figure. make this axes invisible, so you don't see it later in the plot. add two "helping - lines", one solid and one dotted.

    How do you get a legend title? ›

    It is obtained by completing the Quest of Honor and can be temporarily removed for 24 hours by consuming a Golden Apple or by unchecking 'of Legend' from the Title window which can be found by wrenching oneself.

    How do you rename a legend title? ›

    Select your chart and on the Chart Design tab, choose Select Data. Choose on the legend name you want to change in the Select Data Source dialog box, and select Edit. Note: You can update Legend Entries and Axis Label names from this view, and multiple Edit options might be available.

    How do you title something in MATLAB? ›

    title( titletext ) adds the specified title to the current axes or standalone visualization. Reissuing the title command causes the new title to replace the old title. title( titletext , subtitletext ) adds a subtitle underneath the title.

    References

    Top Articles
    Latest Posts
    Article information

    Author: Annamae Dooley

    Last Updated:

    Views: 6191

    Rating: 4.4 / 5 (65 voted)

    Reviews: 80% of readers found this page helpful

    Author information

    Name: Annamae Dooley

    Birthday: 2001-07-26

    Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

    Phone: +9316045904039

    Job: Future Coordinator

    Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

    Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.