Hauptinhalt

A key aspect to masting MATLAB Graphics is getting a hang of the MATLAB Graphics Object Hierarchy which is essentially the structure of MATLAB figures that is used in the rendering pipeline. The base object is the Graphics Root (see groot) which contains the Figure. The Figure contains Axes or other containers such as a Tiled Chart Layout (see tiledlayout). Then these Axes can contain graphics primatives (the objects that contain data and get rendered) such as Lines or Patches.
Every graphics object has two important properties, the "Parent" and "Children" properties which can be used to access other objects in the tree. This can be very useful when trying to customize a pre-built chart (such as adding grid lines to both axes in an eye diagram chart) or when trying to access the axes of a non-current figure via a primative (so "gca" doesn't help out).
One last Tip and Trick with this is that you can declare graphics primatives without putting them on or creating an Axes by setting the first input argument to "gobjects(0)" which is an empty array of placeholder graphics objects. Then, when you have an Axes to plot the primitive on and are ready to render it, you can set the "Parent" of the object to your new Axes.
For Example:
l = line(gobjects(0), 1:10, 1:10);
...
...
...
l.Parent = gca;
Practicing navigating and exploring this tree will help propel your understanding of plotting in MATLAB.
Quick answer: Add set(hS,'Color',[0 0.4470 0.7410]) to code line 329 (R2023b).
Explanation: Function corrplot uses functions plotmatrix and lsline. In lsline get(hh(k),'Color') is called in for cycle for each line and scatter object in axes. Inside the corrplot it is also called for all axes, which is slow. However, when you first set the color to any given value, internal optimization makes it much faster. I chose [0 0.4470 0.7410], because it is a default color for plotmatrix and corrplot and this setting doesn't change a behavior of corrplot.
Suggestion for a better solution: Add the line of code set(hS,'Color',[0 0.4470 0.7410]) to the function plotmatrix. This will make not only corrplot faster, but also any other possible combinations of plotmatrix and get functions called like this:
h = plotmatrix(A);
% set(h,'Color',[0 0.4470 0.7410])
for k = 1:length(h(:))
get(h(k),'Color');
end
Adam Danz just launched a new blog about MATLAB Graphics and App Building.
As you know, He has been a prolific contributor to MATLAB Answers and one of his answers recently won the Editor's Choice Award.
If there are any topics or questions you are interested in, please share with Adam, and I am sure he will get those into his blog.
Adam Danz
Adam Danz
Last activity am 6 Mär. 2024

I'm curious how the community uses the hold command when creating charts and graphics in MATLAB. In short, hold on sets up the axes to add new objects to the axes while hold off sets up the axes to reset when new objects are added.
When you use hold on do you always follow up with hold off? What's your reasoning on this decision?
Can't wait to discuss this here! I'd love to hear from newbies and experts alike!
New in R2022b: GridSizeChangedFcn
tiledlayout() creates a TiledChartLayout object that defines a gridded layout of axes within a figure. When using the 'flow' option, the grid size becomes dynamic and updates as axes are added or as the figure size changes. These features were introduced in R2019b and if you're still stuck on using subplot, you're missing out on several other great features of tiledlayout.
Starting in MATLAB R2022b you can define a callback function that responds to changes to the grid size in flow arrangements by setting the new gridSizeChangedFcn.
Use case
I often use a global legend to represent data across all axes within a figure. When the figure is tall and narrow, I want the legend to be horizontally oriented at the bottom of the figure but when the figure is short and wide, I prefer a vertically oriented legend on the right of the figure. By using the gridSizeChangedFcn, now I can update the legend location and orientation when the grid size changes.
Demo
gridSizeChangeFcn works like all other graphics callback functions. In this demo, I've named the gridSizeChangedFcn "updateLegendLayout", assigned by an anonymous function. The first input is the TiledChartLayout object and the second input is the event object that indicates the old and new grid sizes. The legend handle is also passed into the function. Since all of the tiles contain the same groups of data, the legend is based on data in the last tile.
As long as the legend is valid, the gridSizeChangedFcn updates the location and orientation of the legend so that when the grid is tall, the legend will be horizontal at the bottom of the figure and when the grid is wide, the legend will be vertical at the right of the figure.
Since the new grid size is available as a property in the TiledChartLayout object, I chose not to use the event argument. This way I can directly call the callback function at the end to update the legend without having to create an event.
Run this example from an m-file. Then change the width or height of the figure to demonstrate the legend adjustments.
% Prepare data
data1 = sort(randn(6))*10;
data2 = sort(randn(6))*10;
labels = ["A","B","C","D","E","F"];
groupLabels = categorical(["Control", "Test"]);
% Generate figure
fig = figure;
tcl = tiledlayout(fig, "flow", TileSpacing="compact", Padding="compact");
nTiles = height(data1);
h = gobjects(1,nTiles);
for i = 1:nTiles
ax = nexttile(tcl);
groupedData = [data1(i,:); data2(i,:)];
h = bar(ax,groupLabels, groupedData, "grouped");
title(ax,"condition " + i)
end
title(tcl,"GridSizeChangedFcn Demo")
ylabel(tcl,"Score")
legh = legend(h, labels);
title(legh,"Factors")
% Define and call the GridSizeChangeFcn
tcl.GridSizeChangedFcn = @(tclObj,event)updateLegendLayout(tclObj,event,legh);
updateLegendLayout(tcl,[],legh);
% Manually resize the vertical and horizontal dimensions of the figure
function updateLegendLayout(tclObj,~,legh)
% Evoked when the TiledChartLayout grid size changes in flow arrangements.
% tclObj - TiledChartLayout object
% event - (unused in this demo) contains old and new grid size
% legh - legend handle
if isgraphics(legh,'legend')
if tclObj.GridSize(1) > tclObj.GridSize(2)
legh.Layout.Tile = "south";
legh.Orientation = "horizontal";
else
legh.Layout.Tile = "east";
legh.Orientation = "vertical";
end
end
end
Give it a shot in MATLAB R2022b
  • Replace the legend with a colorbar to update the location and orientation of the colorbar.
  • Define a GridSizeChangedFcn within the loop so that it is called every time a tile is added.
  • Create a figure with many tiles (~20) and dynamically set a color to each row of axes.
  • Assign xlabels only to the bottom row of tiles and ylabels to only the left column of tiles.
Learn about other new features
This article is attached as a live script.

Starting in MATLAB R2022a, use the append option in exportgraphics to create GIF files from animated axes, figures, or other visualizations.

This basic template contains just two steps:

% 1. Create the initial image file
gifFile = 'myAnimation.gif';
exportgraphics(obj, gifFile);
% 2. Within a loop, append the gif image
for i = 1:20
      %   %   %   %   %   %    % 
      % Update the figure/axes %
      %   %   %   %   %   %    % 
      exportgraphics(obj, gifFile, Append=true);
  end

Note, exportgraphics will not capture UI components such as buttons and knobs and requires constant axis limits.

To create animations of images or more elaborate graphics, learn how to use imwrite to create animated GIFs .

Share your MATLAB animated GIFs in the comments below!

See Also

This Community Highlight is attached as a live script

You've spent hours designing the perfect figure and now it's time to add it to a presentation or publication but the font sizes in the figure are too small to see for the people in the back of the room or too large for the figure space in the publication. You've got titles, subtitles, axis labels, legends, text objects, and other labels but their handles are inaccessible or scattered between several blocks of code. Making your figure readable no longer requires digging through your code and setting each text object's font size manually.

Starting in MATLAB R2022a, you have full control over a figure's font sizes and font units using the new fontsize function (see release notes ).

Use fontsize() to

  • Set FontSize and FontUnits properties for all text within specified graphics objects
  • Incrementally increase or decrease font sizes
  • Specify a scaling factor to maintain relative font sizes
  • Reset font sizes and font units to their default values . Note that the default font size and units may not be the same as the font sizes/units set directly with your code.

When specifying an object handle or an array of object handles, fontsize affects the font sizes and font units of text within all nested objects.

While you're at it, also check out the new fontname function that allows you to change the font name of objects in a figure!

Give the new fontsize function a test drive using the following demo figure in MATLAB R2022a or later and try the following commands:

% Increase all font sizes within the figure by a factor of 1.5
fontsize(fig, scale=1.5)
% Set all font sizes in the uipanel to 16
fontsize(uip, 16, "pixels")
% Incrementally increase the font sizes of the left two axes (x1.1)
% and incrementally decrease the font size of the legend (x0.9)
fontsize([ax1, ax2], "increase")
fontsize(leg, "decrease")
% Reset the font sizes within the entire figure to default values
fontsize(fig, "default")
% Create fake behavioral data
rng('default')
fy = @(a,x)a*exp(-(((x-8).^2)/(2*3.^2)));
x = 1 : 0.5 : 20;
y = fy(32,x);
ynoise = y+8*rand(size(y))-4;
selectedTrial = 13;
% Plot behavioral data
fig = figure('Units','normalized','Position',[0.1, 0.1, 0.4, 0.5]);
movegui(fig, 'center')
tcl = tiledlayout(fig,2,2); 
ax1 = nexttile(tcl); 
hold(ax1,'on')
h1 = plot(ax1, x, ynoise, 'bo', 'DisplayName', 'Response');
h2 = plot(ax1, x, y, 'r-', 'DisplayName', 'Expected');
grid(ax1, 'on')
title(ax1, 'Behavioral Results')
subtitle(ax1, sprintf('Trial %d', selectedTrial))
xlabel(ax1, 'Time (seconds)','Interpreter','Latex')
ylabel(ax1, 'Responds ($\frac{deg}{sec}$)','Interpreter','Latex')
leg = legend([h1,h2]);
% Plot behavioral error
ax2 = nexttile(tcl,3);
behavioralError = ynoise-y; 
stem(ax2, x, behavioralError)
yline(ax2, mean(behavioralError), 'r--', 'Mean', ...
    'LabelVerticalAlignment','bottom')
grid(ax2, 'on')
title(ax2, 'Behavioral Error')
subtitle(ax2, ax1.Subtitle.String)
xlabel(ax2, ax1.XLabel.String,'Interpreter','Latex')
ylabel(ax2, 'Response - Expected ($\frac{deg}{sec}$)','Interpreter','Latex')
% Simulate spike train data
ntrials = 25; 
nSamplesPerSecond = 3; 
nSeconds = max(x) - min(x); 
nSamples = ceil(nSeconds*nSamplesPerSecond);
xTime = linspace(min(x),max(x), nSamples);
spiketrain = round(fy(1, xTime)+(rand(ntrials,nSamples)-.5));
[trial, sample] = find(spiketrain);
time = xTime(sample);
% Spike raster plot
axTemp = nexttile(tcl, 2, [2,1]);
uip = uipanel(fig, 'Units', axTemp.Units, ...
    'Position', axTemp.Position, ...
    'Title', 'Neural activity', ...
    'BackgroundColor', 'W');
delete(axTemp)
tcl2 = tiledlayout(uip, 3, 1);
pax1 = nexttile(tcl2); 
plot(pax1, time, trial, 'b.', 'MarkerSize', 4)
yline(pax1, selectedTrial-0.5, 'r-', ...
    ['\leftarrow Trial ',num2str(selectedTrial)], ...
    'LabelHorizontalAlignment','right', ...
    'FontSize', 8); 
linkaxes([ax1, ax2, pax1], 'x')
pax1.YLimitMethod = 'tight';
title(pax1, 'Spike train')
xlabel(pax1, ax1.XLabel.String)
ylabel(pax1, 'Trial #')
% Show MRI
pax2 = nexttile(tcl2,2,[2,1]); 
[I, cmap] = imread('mri.tif');
imshow(I,cmap,'Parent',pax2)
hold(pax2, 'on')
th = 0:0.1:2*pi; 
plot(pax2, 7*sin(th)+84, 5*cos(th)+90, 'r-','LineWidth',2)
text(pax2, pax2.XLim(2), pax2.YLim(1), 'ML22a',...
    'FontWeight', 'bold', ...
    'Color','r', ...
    'VerticalAlignment', 'top', ...
    'HorizontalAlignment', 'right', ...
    'BackgroundColor',[1 0.95 0.95])
title(pax2, 'Area of activation')
% Overall figure title
title(tcl, 'Single trial responses')

This Community Highlight is attached as a live script.