How to create a new figure in MATLAB? - matlab

Usually when I plot in MATLAB, it always draws on the same figure. How do I make it draw in a new figure?
I know it is pretty elementary, but I'm not finding it using Google Search.

figure;
plot(something);
or
figure(2);
plot(something);
...
figure(3);
plot(something else);
...
etc.

While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.
Example: you have five figures on your desktop from a previous script you ran and you use
figure(1);
plot(...)
figure(2);
plot(...)
You just plotted over the figures on your desktop. However the code
figure;
plot(...)
figure;
plot(...)
just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.

The other thing to be careful about, is to use the clf (clear figure) command when you are starting a fresh plot. Otherwise you may be plotting on a pre-existing figure (not possible with the figure command by itself, but if you do figure(2) there may already be a figure #2), with more than one axis, or an axis that is placed kinda funny. Use clf to ensure that you're starting from scratch:
figure(N);
clf;
plot(something);
...

As has already been said: figure will create a new figure for your next plots. While calling figure you can also configure it. Example:
figHandle = figure('Name', 'Name of Figure', 'OuterPosition',[1, 1, scrsz(3), scrsz(4)]);
The example sets the name for the window and the outer size of it in relation to the used screen.
Here figHandle is the handle to the resulting figure and can be used later to change appearance and content. Examples:
Dot notation:
figHandle.PaperOrientation = 'portrait';
figHandle.PaperUnits = 'centimeters';
Old Style:
set(figHandle, 'PaperOrientation', 'portrait', 'PaperUnits', 'centimeters');
Using the handle with dot notation or set, options for printing are configured here.
By keeping the handles for the figures with distinc names you can interact with multiple active figures. To set a existing figure as your active, call figure(figHandle). New plots will go there now.

Another common option is when you do want multiple plots in a single window
f = figure;
hold on
plot(x1,y1)
plot(x2,y2)
...
plots multiple data sets on the same (new) figure.

As simple as this-
figure, plot(yourfigure);

Related

How to have diferent markers and line styles while plotting same variable from multiple data files?

How can I have diferent markers or line styles when I am plotting same variable from 8 diferent data files in one figure?
I have got my code that reads multiple excel files and it is perfectly fine with plotting the variable I call for from all 8 diferent excel files.
Although I already have the plot with different colors that I have defined. However, somehow, I cannot define any marker or diferent Line Styles. I have attached my plotting codes below; please also see the figure
ax = gca;
grid on;
hold on
plot(Pin_dBm,Pout_Meas_dbm,"LineWidth",2)
%ax.LineStyleOrder={'-o','-+','-*','-x','-s','-d','-v','->'};
ax.ColorOrder=[1 0 0; 1 0 1; 0 1 0; 0.4660 0.6740 0.1880; 0 0 1; 0.3010 0.7450 0.9330; 0.8500 0.3250 0.0980; 0.9290 0.6940 0.1250]
ylabel('Output Power [dBm]','Color','K')
xlabel('Input Power [dBm]')
title('Output Power comparison - ON mode (0V)', 'Color', 'k')
legend('3F50Sa1','3F100Sa1', '5F50Sa1','5F100Sa1','7F50Sa1','7F100Sa1','9F50Sa1','9F100Sa1','location', 'bestoutside')
To change trace (or marker) properties you have to use the plot handle, not the figure handle, to change line properties like LineWidth and Color.
To grab the plot handle you have to plot like this
hf1=figure(1)
ax = gca;
grid on;
hp1=plot(Pin_dBm,Pout_Meas_dbm)
hp1.LineWidth=2
hp1.Color='r' % red
..
hf1 is the figure handle, not the trace or curve or graph handle.
The figure is the frame containing traces.
You don't have to, this is ok
hf1=figure
but it's good practice to number figures figure(n) as soon as generated, it helps reading code if later on someone has to findout what figure handle belongs to what figure.
now you tell the graph container, the figure with handle hf1 not to remove the 1st trace regardless of what you plot next:
hold(ax1,'on')
and now, with a for loop or one by one, or in any other way you choose, you can add more traces onto same figures changing the properties you choose using a different plot handle
hp2=plot(Pin_dBm2,Pout_Meas_dbm2)
hp2.LineWidth=1.5
hp1.Color='b' % blue
..
and as you mention in your question you can send the same variable updated with different input data or file
update_Pin_dBm;
update_Pout_Meas_dbm;
If you do not update Pin_dBm and-or Pout_Meas_dbm the next plot with different properties may be identical or similar and overlap the previous trace.
hp3=plot(Pin_dBm,Pout_Meas_dbm)
hp3.LineWidth=1
hp1.Color=[0 1 1] % cyan
The figure handle hf1 could still be used to change trace properties, because as the container to the plot, has as children property the handle to the plot. But no one uses what is otherwise a rather long Java-like expression
Note: The term marker is generally used, not for the graph line, the plot, but for the pointers on the graph line that scopes and also MATLAB allows to put, to read a particular (x,y).
If you find this answer useful, would you please be so kind to accept it?
Thanks for reading my answer.

Combine figures with subplots into one figure

Having done several simulations on a cluster, where each simulation saves a figure, I want to combine these figures into a single figure.
For ease, assume we have the two figures:
x = 0:0.01:.2;
subplot(1,3,1)
plot(x,sin(x))
legend('sin(x)')
subplot(1,3,2)
plot(x,cos(x))
legend('cos(x)')
subplot(1,3,3)
plot(x,tan(x))
legend('tan(x)')
and
x = 0:0.01:.2;
subplot(1,3,1)
plot(x,x,'r')
legend('x')
subplot(1,3,2)
plot(x,1-x.^2/2,'r')
legend('1-x.^2/2')
subplot(1,3,3)
plot(x,x,'r')
legend('x')
saved as figure1.fig and figure2.fig. I would now like to combine these two plots into a single figure with 3 subplots, the same colouring and legends. Is there an easy way to do this?
Open both the figures and copy the objects of one figure to the other.
hf1 = openfig('figure1.fig');
hf2 = openfig('figure2.fig'); set(hf2, 'Visible', 'off');
for k=1:numel(hf1.Children)
copyobj(hf2.Children(k).Children, hf1.Children(k)); %Copying objects to figure1
end
Result for the provided sample data is:
The plots may be too similar to be noticed which is due to the provided sample data itself.
From the figure menu File -> Generate Code ..., you can generate code to create the figure. Then you can modify it (subplot index and location) according to your need to combine with another figure.
I did not a find a command to generate code through.

Creating annotation boxes for subplots in a for-loop in Matlab

I have the following code in Matlab that runs through a for loop, reads data from a file and plots 9 different figures, that correspond to some particular "channels" in my data, so I decided to annotate them in the for loop.
clear
clc
for i=1:9
subplot(3,3,i);
hold on
x = [4 13]; % from your example
y = ([1 1]); % from your example
y2 = ([-0.4 -0.4]);
H=area(x,y,'LineStyle','none',...
'FaceColor',[1 0.949019610881805 0.866666674613953]);
H1=area(x,y2,'LineStyle','none',...
'FaceColor',[1 0.949019610881805 0.866666674613953]);
% Create textbox
annotation('textbox',...
[0.719849840255583 0.603626943005185 0.176316293929713 0.308290155440411],...
'String',{'FABLIGHT04','Channel',i},...
'FontWeight','bold',...
'FontSize',10,...
'FontName','Geneva',...
'FitBoxToText','off',...
'EdgeColor','none');
axis([0 24 -0.4 1])
set(gca,'XTick',[0:1:24])
set(gca,'YTick',[-0.4:0.2:1])
xlabel('Time (s)');
end
Initially it was giving me 9 different figures and the annotation thing worked fine. But I wanted to be able to tile them onto a subplot for easier comparison.
Since I switched over to using subplot, it does not annotate my figure properly. On opening the editing dock and generating the code, I find that matlab is plotting everything first and then just putting the annotation boxes in the same figure, one on top of the other. Looking at the code it generated, it apparently takes this part of the code:
annotation('textbox',...
[0.719849840255583 0.603626943005185 0.176316293929713 0.308290155440411],...
'String',{'FABLIGHT04','Channel',i},...
'FontWeight','bold',...
'FontSize',10,...
'FontName','Geneva',...
'FitBoxToText','off',...
'EdgeColor','none');
and does it as:
annotation(figure1,'textbox'...)
etc etc
So for all 9 text boxes, it puts them onto the same figure. I tried to do S=subplot(3,3,i) then annotation(S,'textbox') etc etc, I have also tried S(i)=subplot(3,3,i) and then annotation(S,'textbox') etc etc but nothing seems to work.
I have also tried to change the location of the box. I can't seem to figure out how to make it smaller either.
Does anyone know how to have annotation boxes in the right subplot in a for loop?
Thanks
I'm afraid annotation objects are properties of figures and NOT axes, as such its harder to customize the position of each annotation objects because no matter how many subplots you have, they are all part of the same figure and you need to specify their position relatively to the figure coordinate system.
Therefore, you can manually set the position of each text box in your code depending on the subplot it belongs to...
Simple example:
clear
clc
close all
figure('Units','normalized'); %// new figure window
for k = 1:2
str = sprintf('Subplot %d',k);
subplot(1,2,k)
plot(rand(1,10));
%// Customize position here
hAnnot(k) = annotation('textbox', [k*.4-.2 .6 .1 .1],...
'String', str,'FontSize',14);
end
Which looks like this:
Its not very elegant but I'm personally not aware of any other option if you do need to use annotations objects. A less cumbersome alternative would be to use a simple text objects, which are properties of axes and therefore much more friendly to position :)
Hope that helps!

Plotting an existing MATLAB plot into another figure

I used the plot command to plot a figure and then changed lots of its properties using set command. I also store the handle of the plot (say h1).
What I need is to use the handle to plot the same figure again later in my code. I checked the plot command and did not find any version that accepts handle. I also thought of getting the Xdata and Ydata and use them to re-plot the same figure.
What is the simplest solution?
Edit 1: A working sample code based on copyobj that PeterM suggested.
hf(1) = figure(1);
plot(peaks);
hf(2) = figure(2);
plot(membrane);
hf(3) = figure(3);
ha(1) = subplot(1,2,1);
ha(2) = subplot(1,2,2);
for i = 1:2
hc = get(hf(i),'children');
hgc = get(hc, 'children');
copyobj(hgc,ha(i));
end
Edit 2: I also found this function that can copy figures (including legend) into a subplot.
I have run into this situation before. Depending on what you are trying to do the function copyobj may be appropriate. This function lets you take the contents of one axes and copy it to a new figure.
Improving #PeterM nice answer, one easier way would be:
fig2H=copy(gcf) % or change gcf to your figure handle
But it depends on what you want, if you want only the axes, or the whole figureā€¦ (btw, it doesn't seem to copy the legend handle).
You can use saveas to save the figure in a file, and the open to load the exact same figure from this file.
This would be the laziest way to accomplish what you want.
% Sample plot
f1 = figure(1);
plot(0:0.1:2*pi, sin(0:0.1:2*pi));
f2 = figure(2);
% The code you need
saveas(f1, 'temp.fig')
f2 = hgload('temp.fig')
delete('temp.fig')
I have used the function figs2subplots (given in Edit2 in the original question) - it does the work and is very easy to use.

How do I hide axes and ticks in matlab without hiding everything else

I draw images to axes in my matlab UI, but I don't want the axes and ticks to be visible how do I prevent that, and also where do I make this call?
I do this
imagesc(myImage,'parent',handles.axesInGuide);
axis off;
Is this what you are looking for?
This is definitely somewhere else on this website and in the matlab documentation. Try typing
help plot
Or using the documentation on plotting!
edit: Now that you have shown what you are doing. (You don't need the handles, I just always write them in to clutter my workspace)
myImage = yurbuds0x2Dironman; # don't ask
fH = figure;
iH = imagesc(myImage);
set(gca,'xtick',[],'ytick',[])
Are you able to do it like this?
I support the
set(gca,'xtick',[],'ytick',[]);
approach over the
axis off
one. The reason is set(gca, ...) just removes the labels but keeps the axes, unlike axis off. I am generating a group of images with fixed dimensions to combine later into a video. Deleting the axes creates different size frames that can't be recombined.