Handling multiple plots in MATLAB - matlab

I am using plot(X) whereX is an n-by-k matrix, which produces k plots with n points.
How do I show the legend for this plot? More importantly, is there an easy way to show checkboxes to show or not show certain plots?

I think you can find this section of Documentation useful.
GUI that Displays and Graphs Tabular Data
http://www.mathworks.com/help/techdoc/creating_guis/bropmbk-1.html
Please use this body for plot_callback function in tableplot.m file to get a dirty implementation of the flexible legend.
function plot_callback(hObject, eventdata, column)
% hObject Handle to Plot menu
% eventdata Not used
% column Number of column to plot or clear
colors = {'b','m','r'}; % Use consistent color for lines
colnames = get(htable, 'ColumnName');
colname = colnames{column};
lgidx = get(haxes, 'UserData');
if isempty(lgidx)
lgidx = false(size(colnames));
end
if get(hObject, 'Value')
% Turn off the advisory text; it never comes back
set(hprompt, 'Visible', 'off')
% Obtain the data for that column
ydata = get(htable, 'Data');
set(haxes, 'NextPlot', 'Add')
% Draw the line plot for column
hplot = plot(haxes, ydata(:,column),...
'DisplayName', colname,...
'Color', colors{column});
lgidx(column) = true;
else % Adding a line to the plot
% Find the lineseries object and delete it
hplot = findobj(haxes, 'DisplayName', colname);
lgidx(column) = false;
delete(hplot);
end
if any(lgidx)
legend(haxes, colnames{lgidx} );
else
legend(haxes, 'off')
end
set(haxes, 'UserData', lgidx);
end

An example:
x = cumsum(rand(100,3)-0.5); %# three series with 100 points each
h = plot(x);
legend(h, {'first' 'second' 'third'})

Related

How to set the errorbars in a different color from the plot in Matlab?

When making a plot in Matlab using errorbar(...) the color of the error bars is the same as the plot. How do I set them to be in a different color?
I tried looking for a way to do it in here:
https://www.mathworks.com/help/matlab/ref/matlab.graphics.chart.primitive.errorbar-properties.html
https://www.mathworks.com/help/matlab/ref/errorbar.html
But I couldn't find it.
Edit: This question:
Color of errobar different from the graph matlab
doesn't have the answer to what I'm asking. It was asked almost a year and half ago and no solution was given. The one comment there doesn't give a proper solution. It says to draw the plot twice - once with the errorbars (when the plot and the errorbars are at the same color) and a second time just the plot without the errorbars (which will be drawn on top of the first one using hold on). There should be a way to draw the figure once with the errorbars at a different color than the color of the plot - that is what I'm looking for.
Here is a quick and dirty implementation of a function that allows to style the errorbars and the data separatly. However, internally it does the same as the answers to the previously posted question: it uses two plots.
function varargout = mc_errorbar(ax, x,y,e, varargin)
% MC_ERRORBAR errorbar which allows to style errorbar and data separately
%
% Usage:
% mc_errorbar(X,Y,E)
% plots errorbars and a separate line in the current axis.
%
% mc_errorbar(X,Y,E, property, value)
% plots errorbars and a separate line in the current axis and styles
% the plots according to the properties given. All properties that are
% accepted by the errorbar function are allowed, but should be prefixed
% with 'EB'. Note that the LineStyle property will be overriden.
% Properties not prefixed with 'EB' will be passed to the plot
% function, hence all properties allowed by plot are allowed here, too.
%
% mc_errorbar(ax, ___)
% plots in the axes ax instead of the current axes.
%
% [lh] = mc_errorbar(___)
% returns the line handle
%
% [lh, ebh] = mc_errorbar(___)
% returns the line handle and the handle to the errorbar
%
% See also errorbar plot
if ~isa(ax, 'matlab.graphics.axis.Axes')
if nargin > 3
varargin = [{e}, varargin(:)'];
end
e = y;
y = x;
x = ax;
ax = gca();
end
oldnextplot = ax.NextPlot;
ebargs = {};
lineargs = {};
for k = 1:2:numel(varargin)
if strcmp(varargin{k}(1:2),'EB') == 1
ebargs{end+1} = varargin{k}(3:end);
ebargs{end+1} = varargin{k+1};
else
lineargs{end+1} = varargin{k};
lineargs{end+1} = varargin{k+1};
end
end
ebargs{end+1} = 'LineStyle';
ebargs{end+1} = 'none';
eb = errorbar(ax, x, y, e, ebargs{:});
ax.NextPlot = 'add';
line = plot(ax, x,y, lineargs{:});
ax.NextPlot = oldnextplot;
if nargout > 0
varargout{1} = line;
end
if nargout > 1
varargout{2} = eb;
end
end
Example:
mc_errorbar(1:10, (1:10)*2, (1:10)*.5, 'Color','g', 'EBColor', 'k', 'EBLineWidth', 3, 'LineStyle','-', 'LineWidth',8)

Add non-existent entry to legend

I want to add an entry manually to a MATLAB legend. This legend can be pre-existent and contain other graphed elements' entries, but not necessarily.
I make a scatter plot, but instead of using e.g. scatter(x,y), I plot it using
for n = 1:numel(x)
text(x(n),y(n),num2str(n), ...
'HorizontalAlignment','center','color',[1 0 0])
end
This results in a scatter plot of numbers one through the number of elements in x (and y, because they are of the same size). I want to add a legend entry for these numbers.
I tried to add or edit the legend with
[h,icons,plots,s] = legend(___)
as described on the legend documentation page. I can't figure out how I can add a legend entry, without having to plot something (such as an actual scatter plot or regular plot). I want the usual line or marker symbol in the legend to be a number or character such as 'n', indicating the numbers in the graph. Is this possible and how would one achieve this?
EDIT by Erik
My answer goes below zelanix's answer, because mine is based on it.
Original answer
A fairly workable solution may be as follows:
x = rand(10, 1);
y = rand(10, 1);
figure;
text(x,y,num2str(transpose(1:numel(x))),'HorizontalAlignment','center')
% Create dummy legend entries, with white symbols.
hold on;
plot(0, 0, 'o', 'color', [1 1 1], 'visible', 'off');
plot(0, 0, 'o', 'color', [1 1 1], 'visible', 'off');
hold off;
% Create legend with placeholder entries.
[h_leg, icons] = legend('foo', 'bar');
% Create new (invisible) axes on top of the legend so that we can draw
% text on top.
ax2 = axes('position', get(h_leg, 'position'));
set(ax2, 'Color', 'none', 'Box', 'off')
set(ax2, 'xtick', [], 'ytick', []);
% Draw the numbers on the legend, positioned as per the original markers.
text(get(icons(4), 'XData'), get(icons(4), 'YData'), '1', 'HorizontalAlignment', 'center')
text(get(icons(6), 'XData'), get(icons(6), 'YData'), '2', 'HorizontalAlignment', 'center')
axes(ax1);
Output:
The trick to this is that the new axes are created in exactly the same place as the legend, and the coordinates of the elements of the icons are in normalised coordinates which can now be used inside the new axes directly. Of course you are now free to use whatever font size / colour / whatever you need.
The disadvantage is that this should only be called after your legend has been populated and positioned. Moving the legend, or adding entries will not update the custom markers.
Erik's answer
Based on zelanix's answer above. It is a work-in-progress answer, I am trying to make a quite flexible function of this. Currently, it's just a script that you'd need to adapt to your situation.
% plot some lines and some text numbers
f = figure;
plot([0 1],[0 1],[0 1],[1 0])
x = rand(25,1);
y = rand(25,1);
for n = 1:numel(x)
text(x(n),y(n),num2str(n), ...
'HorizontalAlignment','center','color',[1 0 0])
end
hold on
% scatter(x,y) % used to test the number positions
scatter(x,y,'Visible','off') % moves the legend location to best position
% create the dummy legend using some dummy plots
plot(0,0,'o','Visible','off')
[l,i] = legend('some line','some other line','some numbers','location','best');
l.Visible = 'off';
% create empty axes to mimick legend
oa = gca; % the original current axes handle
a = axes;
axis manual
a.Box = 'on';
a.XTick = [];
a.YTick = [];
% copy the legend's properties and contents to the new axes
a.Units = l.Units; % just in case
a.Position = l.Position;
i = copyobj(i,a);
% replace the marker with a red 'n'
s = findobj(i,'string','some numbers');
% m = findobj(i(i~=s),'-property','YData','marker','o');
m = findobj(i(i~=s),'-property','YData');
sy = s.Position(2);
if numel(m)>1
dy = abs(m(1).YData - sy);
for k = 2:numel(m)
h = m(k);
dy2 = abs(h.YData - sy);
if dy2<dy
kbest = k;
dy = dy2;
end
end
m = m(kbest);
end
m.Visible = 'off';
mx = m.XData;
text(mx,sy,'n','HorizontalAlignment','center','color',[1 0 0])
% reset current axes to main axes
f.CurrentAxes = oa;
The result:

Print ONLY plot on MATLAB GUI

How can I print ONLY the plot created by my MATLAB GUI into a PDF document?
I know about the function available online called export_fig, but we are not allowed to make use of externally coded tools for this.
I currently have the following
function PrintButton_Callback(hObject, eventdata, handles)
set(gcf,'PaperType','A4','PaperOrientation','landscape','PaperPositionMode','auto');
print(get(handles.Axes,'Parent'), '-dpdf','Results.pdf');
However, this results in my entire GUI figure being saved.
How can I select ONLY the plot made by my axes ("Axes")?
The print command only accepts a figure as handle parameter ...
To print specified axis only a trick is to copy this axis to a new temporary figure using copyobj and use print command on the new figure.
Here is some sample code:
%% -- Test code
function [] = TestPrint()
%[
% Create figure with two axes
fig = figure(1); clf;
ax1 = subplot(1,2,1);
plot(rand(1, 12));
ax2 = subplot(1,2,2);
plot(rand(1, 12));
% Print the whole figure
print(fig, '-dpdf', 'figure.pdf');
% Print ONLY second axis
printAxis(ax2, '-dpdf', 'axis.pdf');
%]
end
%% --- Print specified axis only
% NB: Accept same arguments as 'print' except for first one which now is an axis.
function [] = printAxis(ax, varargin)
%[
% Create a temporary figure
visibility = 'on'; % You can set it to off if you want
tempFigure = figure('Visible', visibility);
cuo = onCleanup(#()clearTempFigure(tempFigure)); % Just to be sure to destroy the figure
% Copy selected axis to the temporary figure
newAx = copyobj(ax, tempFigure);
% Make it fill whole figure space
set(newAx, 'OuterPosition', [0 0 1 1]);
% Print temporary figure
print(tempFigure, varargin{1:end});
%]
end
function [] = clearTempFigure(h)
%[
if (ishandle(h)), delete(h); end
%]
end
Disable axes visibility: set(gca,'Visible','off') before printing.

Skipping a legend in a plot loop [duplicate]

t = 0 : 0.01 : 2 * pi;
s = sin(t);
c = cos(t);
m = -sin(t);
hold on;
plot(t, s, 'r');
plot(t, c, 'b');
plot(t, m, 'g');
hold off;
legend('', 'cosine', '');
There are several curves in my plotting. I want to display legend for only some of them. How do I do it?
For example, how do I make only the legend for the cosine curve visible in the plotting above? When I call the legend() functions as legend('', 'cosine'); instead of adding the empty third parameter, indeed the third green line is removed from the legend. But that doesn't solve my problem, because the undesired red line stays visible.
I do not like storing the handle values, it becomes a mess when I have a lot of graphs in my figures. Therefore i found another solution.
t = 0 : 0.01 : 2 * pi;
s = sin(t);
c = cos(t);
m = -sin(t);
hold on;
plot(t, s, 'r', 'HandleVisibility','off'); % Plotting and telling to hide legend handle
h2 = plot(t, c, 'b', 'DisplayName', 'cosine'); % Plotting and giving legend name
plot(t, m, 'g', 'HandleVisibility','off'); % Plotting and telling to hide legend handle
legend show % Generating legend based on already submitted values
This give me the same graph as shown in Eitan T's answer.
It should be noted that this will affect other matlab functions also, for example will cla only remove the plots mentioned on the legend. Search for HandleVisibility in the Matlab documentation for more about that.
Just store the desired legend handles in a variable and pass the array to legend. In your case, it would only be one value, like so:
hold on;
plot(t, s, 'r');
h2 = plot(t, c, 'b'); % # Storing only the desired handle
plot(t, m, 'g');
hold off;
legend(h2, 'cosine'); % # Passing only the desired handle
You should get this plot:
Let's start with your variables and plot them:
t = 0 : 0.01 : 2 * pi;
s = sin(t);
c = cos(t);
m = -sin(t);
figure;
hold ('all');
hs = plot(t, s);
hc = plot(t, c);
hm = plot(t, m);
There is a property called IconDisplayStyle. It is buried quite deep. The path you need to follow is:
Line -> Annotation -> LegendInformation -> IconDisplayStyle
Setting the IconDisplayStyle property off will let you skip that line. As an example, I am going to turn off hs's legend.
hsAnno = get(hs, 'Annotation');
hsLegend = get(hsAnno, 'LegendInformation');
set(hsLegend, 'IconDisplayStyle', 'off');
Of course you can go ahead and do it like this:
set(get(get(hs, 'Annotation'), 'LegendInformation'), 'IconDisplayStyle', 'off');
But I find it much harder to understand.
Now, the legend function will just skip hs.
Ending my code with this:
legend('cosine', 'repeat for this handle')
will give you this:
EDIT: Jonas had a nice suggestion in the comments:
Setting the DisplayName property of hc like this:
set(hc, 'DisplayName', 'cosine');
legend(gca, 'show');
will give you the legend you need. You will have associated your line handle with 'cosine'. So, you can just call the legend with 'off' or 'show' parameters.
You could just change the order in wich the curves are plotted and apply the legend to the first curve:
t = 0 : 0.01 : 2 * pi;
s = sin(t);
c = cos(t);
m = -sin(t);
plot(t,c,t,s,t,m) % cosine is plotted FIRST
legend('cosine') % legend for the FIRST element
if i'd want to put in a legend for cosine and -sine:
plot(t,c,t,m,t,s) % cosine and -sine are first and second curves
legend('cosine', '-sine')
To expand Sebastian's answer, I have a special case where I'm plotting several lines in one of two formats (truss beams either in compression or tension) and was able to plot specific plot handles in the legend as long as the labels were the same length
for ii=1:nBeams
if X(ii)<0 %Bars with negative force are in compession
h1=plot(linspace(beamCord(ii,1),beamCord(ii,3)),...
linspace(beamCord(ii,2),beamCord(ii,4)),'r:');
elseif X(ii)>0 %Bars with positive force are in tension
h2=plot(linspace(beamCord(ii,1),beamCord(ii,3)),...
linspace(beamCord(ii,2),beamCord(ii,4)),'b');
end
end
legend([h1;h2],['Compression';'Tension ']);
Where 4 spaces have been added behind 'Tension' so that the number of characters is consistent.
Quick in-plot hack:
Cut everything you don't want to appear in the legend
Apply legend
Paste

Several graphs in 1 loop, each iteration adds a line on every figure

Trying to engineer the following in Matlab:
** loop start;
y(:,i) = function of x;
z(:,i) = function of x;
plot(x,y(:,i)) on figure 1, hold all;
plot(x,z(:,i)) on figure 2, hold all;
** loop end;
add title, legend, etc for figure 1 (NB: we have multiple lines);
add title, legend, ets for figure 2 (NB: same, have multiple lines for the legend);`
Tried multiple combinations without much luck. Managed to get 2 figures but only the 2-nd displays multiple lines, not the first. And can't figure how to add legends to these 2 correctly.
Save a handle to each figure, and to each axis object:
fh1 = figure;
hold all;
ah1 = gca;
fh2 = figure;
hold all;
ah2 = gca;
for i=1:N
y(:,i) = function of x;
z(:,i) = function of x;
plot(ah1, x, y(:,i)); %# tell it which axis to use (ah1)
plot(ah2, x, z(:,i)); %# (ah2)
end
legend(ah1, ...) %# legend options here
legend(ah2, ...) %# and the other legend
%# note: you can set figure properties for each using fh1, fh2 handles.
You can do this:
figHandle1 = figure(1);
figHandle2 = figure(2);
Then when you want to plot on that figure do this:
figure(figHandle1) %Plot on figure 1
%ie plot(someStuff)
figure(figHandle2) %Plot on figure 2
Also its the same for the title and stuff, you jjust need to identify which figure by doing:
figure(handle);
Hope this helps.