Specifying limits of axes - matlab

I'm trying to limit x axis, i.e., frequency axis to 4 Hz in MatLab. This is the code I used:
subplot(3,1,2);
%Fse = 220;
time = 0:1/fse:secBuffer-1/fse;
%a = eegCounter;
c = eegBuffer;
wo = 50 / (1000/2);
bw = wo / 60;
[b,a] = iirnotch(wo,bw);
y = filter(b,a,c);
ydft = fft(c);
xdft = fft(y);
xlabel('Frequency');
ylabel('Signal');
xlim([1,4]);
ylim([1,4]);
plot(xdft,ydft);
However mine is live signal plotting and both x axis and y axis keep changing according to incoming packets. How to limit x axis to 4 Hz?

When plotting MATLAB automatically tries to fit the axis with the dynamic range of the data. Therefore if you want to make sure only a given range is plotted, you need to specify it AFTER the call to plot to force MATLAB to do it, otherwise it won't and you will be stuck with the whole data.
Here is a very simple code in which I call xlim either before or after the call to plot. See the difference?
clear
clc
close all
x = 1:50;
y = x.^2;
figure
subplot(1,2,1)
xlim([1 20])
plot(x,y)
title('xlim before call to plot')
subplot(1,2,2)
plot(x,y)
xlim([1 20])
title('xlim after call to plot')
Produces this:

You have to set the XLimMode (and YLimMode) properties of the axes to manual. But even if you do so every call to plot(...) will reset that to auto and mess up your axes limits.
The cleanest way is to first define your axes and your plots outside of any loop (not forgetting to get their handle), then when you update the data just update the XData and YData of the line objects, using the set method. The set method will only update the property you pass in parameters, so it will not modify the XLimMode property.
%// This part of the code should run only once
h.ax = subplot(3,1,2) ; %// get the handle of the axes
h.line = plot(0) ; %// create an empty line plot
set(h.ax , 'XLimMode','manual' , 'XLim',[1 4]) ; %// define the properties of the axes (X)
set(h.ax , 'YLimMode','manual' , 'YLim',[1 4]) ; %// define the properties of the axes (Y)
xlabel('Frequency');
ylabel('Signal');
%//
%// This part of the code is the loop where you calculate and update your plot
%// ...
%// now do your calculations
%// ...
%// when it is time to update, just call:
set( h.line, 'XData',xdft 'YData',ydft ) ;

You can use the function axis as defined there axis function matlab

Related

LogLog plot in MATLAB is not creating a plot [duplicate]

I'm trying to plot a simple graph using for loop as shown below
x=linspace(0,2*pi,100);
for i=1:numel(x)
y=sin(x(i));
plot(x(i),y)
hold on
end
However, nothing appear on my figure. Why is that?
Why this happens...
With plot(x(i),y) you are plotting 100 single points (one in each iteration) and they are not shown by default. Therefore the plot looks empty.
Solution 1: Vectorized calculation and direct plot
I assume you meant to draw a continuous line. In that case no for-loop is needed because you can calculate and plot vectors directly in MATLAB. So the following code does probably what you want:
x = linspace(0,2*pi,100);
y = sin(x);
plot(x,y);
Note that y is a vector as well as x and that y(n) equals to sin(x(n)) for all n. If you want to plot the points itself, use LineSpec-syntax when calling plot like this1:
plot(x,y,'*');
1) Other types of points are possible as well, see the above linked documentation.
Solution 2: Calculate values within for-loop and plot afterwards
If you want to calculate the values within a for-loop and plot it afterwards: Pre-allocate the needed variable (in this case y), calculate the values within the for-loop and finally plot it with one single command after the calculation.
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
end
plot(x,y);
Solution 3: Dynamically update plot while calculating
In case you insist on plotting within each iteration, the previous code from Solution 2 can be expanded as follows: Create a figure, add an 'empty' plot to it and store its handle. Within the for-loop calculate the values and add them to the y-vector as shown above. As a last step you can update the plot by changing its XData and YData properties and calling drawnow. Note that calling plot every time within the for-loop is unnecessarily expensive and I don't recommend it.
% create figure and plot
figure;
ph = plot(0,0);
ax = gca;
set(ax,'XLim',[0,2*pi]);
set(ax,'YLim',[-1,1]);
% calculate and update plot
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
set(ph,'XData',x(1:i));
set(ph,'YData',y(1:i));
drawnow;
end
Simple approach
If you want to draw a curve as you add data, try the following:
x = linspace(0,2 * pi, 100);
y = zeros(size(x));
for i=1:numel(x)
y(i) = sin(x(i));
plot(x(1:i), y(1:i), 'color', 'r')
drawnow();
end
Be aware that the plot automatically tries to set x and y limits (curve is scaled to the plot window), to prevent that you have to manually set the x- and y-limits with xlimand ylim.
As Matt wrote in his answer, calling plot in each iteration is quite expensive (i.e. time consuming). Therefore I suggest using datasources:
Update graph using data sources
% Create a panel and axes object
h_panel = uipanel;
h_axes = axes( 'Parent', h_panel);
% Create data sources
x = linspace(0,2 * pi, 100);
y = zeros(size(x));
% Create graph object, in this case stairs
% and bind the variables x and y as its data sources
h_stairs = stairs(h_axes, x, y, 'XDataSource', 'x', 'YDataSource', 'y');
for i=1:size(x)
y(i) = sin(x(i));
% Update the data of the stairs graph
refreshdata(h_stairs);
drawnow();
end
The call to drawnow isn't neccessary in each iteration, it is only used to update the visuals, so you can see the changes directly.

Matlab: plotting animation with fixed axes

When I call this function, the axes are moving with the plot. How can I stop this from happening? I tried putting xlim and ylim before the function in the command window but that didn't work.
My code is:
function h = plootwithanimation(x,y)
for h = 1:length(x)
plot(x(h),y(h),'*')
pause(1)
hold on
end
Try fixing the bounds using the axis function:
function h = plootwithanimation(x,y)
for h = 1:length(x)
plot(x(h),y(h),'*')
axis([0 10 -2 100]) %or whatever you want. This sets 0<x<10 and -2<y<100
pause(1)
hold on
end
You can fix the bounds by using xlim and ylim as you tried, but plotting will ignore whatever you set the axes to before calling plot.
You should instead use them after the plot
function h = plotwithanimation(x, y, xlims, ylims)
% Also pass in axis limits
% xlims = [x0,x1]
% ylims = [y0,y1]
hold on; % You only have to hold on once around plotting
for h = 1:length(x)
plot(x(h),y(h),'*');
xlim(xlims);
ylim(ylims);
pause(1);
end
hold off; % Good habit so you don't accidentally plot over this figure later

How to specify axes when using the function `fit`

I have two axes: one for viewing images and the other for plotting graphs. I get this error when I try to specify which axes I want to plot the data on: Error using plot. A numeric or double convertible argument is expected when trying plot(handles.axis,curve,x,y).
figure
handles.axis = gca;
x = 1:10;
y = 1:10;
curve = fit(x',y','linearinterp');
plot(curve,x,y) % works fine
plot(handles.axis,curve,x,y) % doesn't work
plot(curve,x,y,'Parent',handles.axis) % doesn't work
You can paste this example into Matlab to try it out. How can the code be corrected in order to specify the axes?
plot in the curve fitting toolbox is not the same as MATLAB's base plot. Though there is a documented syntax for specifying the parent axes for sfit objects, there doesn't seem to be one for cfit objects, which would be returned by your fit call in this case.
However, from the documentation we see that:
plot(cfit) plots the cfit object over the domain of the current axes, if any
So if the current axis is set prior to the plot call it should work as desired. This can be done either by modifying the figure's CurrentAxes property or by calling axes with the handle of an axes object as an input.
% Set up GUI
h.f = figure;
h.ax(1) = axes('Parent', h.f, 'Units', 'Normalized', 'Position', [0.07 0.1 0.4 0.85]);
h.ax(2) = axes('Parent', h.f, 'Units', 'Normalized', 'Position', [0.55 0.1 0.4 0.85]);
% Set up curve fit
x = 1:10;
y = 1:10;
curve = fit(x', y', 'linearinterp'); % Returns cfit object
axes(h.ax(2)); % Set right axes as CurrentAxes
% h.f.CurrentAxes = h.ax(2); % Set right axes as CurrentAxes
plot(curve, x, y);
I refine my answer as follows:
It looks that the plot function in matlab does not like a fit object after an axis followed by two vectors. In such case, I would do something like this:
x = 1:10;
y = 1:10;
figure % new figure
ax1 = subplot(2,1,1);
ax2 = subplot(2,1,2);
curve = fit(x',y','linearinterp');
plot(ax1,x,curve(x));
hold on;plot(ax1,x,y,'o') % works fine
plot(ax2,x,curve(x));
hold on;plot(ax2,x,y,'o') % works fine
Actually the trick is to provide x and then curve(x) as two vectors without giving the whole fit-object to the plot function.

Plotting graph using for loop in MATLAB

I'm trying to plot a simple graph using for loop as shown below
x=linspace(0,2*pi,100);
for i=1:numel(x)
y=sin(x(i));
plot(x(i),y)
hold on
end
However, nothing appear on my figure. Why is that?
Why this happens...
With plot(x(i),y) you are plotting 100 single points (one in each iteration) and they are not shown by default. Therefore the plot looks empty.
Solution 1: Vectorized calculation and direct plot
I assume you meant to draw a continuous line. In that case no for-loop is needed because you can calculate and plot vectors directly in MATLAB. So the following code does probably what you want:
x = linspace(0,2*pi,100);
y = sin(x);
plot(x,y);
Note that y is a vector as well as x and that y(n) equals to sin(x(n)) for all n. If you want to plot the points itself, use LineSpec-syntax when calling plot like this1:
plot(x,y,'*');
1) Other types of points are possible as well, see the above linked documentation.
Solution 2: Calculate values within for-loop and plot afterwards
If you want to calculate the values within a for-loop and plot it afterwards: Pre-allocate the needed variable (in this case y), calculate the values within the for-loop and finally plot it with one single command after the calculation.
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
end
plot(x,y);
Solution 3: Dynamically update plot while calculating
In case you insist on plotting within each iteration, the previous code from Solution 2 can be expanded as follows: Create a figure, add an 'empty' plot to it and store its handle. Within the for-loop calculate the values and add them to the y-vector as shown above. As a last step you can update the plot by changing its XData and YData properties and calling drawnow. Note that calling plot every time within the for-loop is unnecessarily expensive and I don't recommend it.
% create figure and plot
figure;
ph = plot(0,0);
ax = gca;
set(ax,'XLim',[0,2*pi]);
set(ax,'YLim',[-1,1]);
% calculate and update plot
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
set(ph,'XData',x(1:i));
set(ph,'YData',y(1:i));
drawnow;
end
Simple approach
If you want to draw a curve as you add data, try the following:
x = linspace(0,2 * pi, 100);
y = zeros(size(x));
for i=1:numel(x)
y(i) = sin(x(i));
plot(x(1:i), y(1:i), 'color', 'r')
drawnow();
end
Be aware that the plot automatically tries to set x and y limits (curve is scaled to the plot window), to prevent that you have to manually set the x- and y-limits with xlimand ylim.
As Matt wrote in his answer, calling plot in each iteration is quite expensive (i.e. time consuming). Therefore I suggest using datasources:
Update graph using data sources
% Create a panel and axes object
h_panel = uipanel;
h_axes = axes( 'Parent', h_panel);
% Create data sources
x = linspace(0,2 * pi, 100);
y = zeros(size(x));
% Create graph object, in this case stairs
% and bind the variables x and y as its data sources
h_stairs = stairs(h_axes, x, y, 'XDataSource', 'x', 'YDataSource', 'y');
for i=1:size(x)
y(i) = sin(x(i));
% Update the data of the stairs graph
refreshdata(h_stairs);
drawnow();
end
The call to drawnow isn't neccessary in each iteration, it is only used to update the visuals, so you can see the changes directly.

Matlab GUI select which axes to plot

I am using the code below to plot data from the serial port. Since I have two axes for plotting, how can I select a particular axes for this plot?
From similar problem, I found that they use axes(handles.axes2);. Since I have the plot declared at the start of the program, where should I place this line of code? I tried placing it before specifying the plot title etc. but it is not working.
% Serial Data Logger
% Yu Hin Hau
% 7/9/2013
% **CLOSE PLOT TO END SESSION
clear
clc
%User Defined Properties
serialPort = 'COM5'; % define COM port #
plotTitle = 'Serial Data Log'; % plot title
xLabel = 'Elapsed Time (s)'; % x-axis label
yLabel = 'Data'; % y-axis label
plotGrid = 'on'; % 'off' to turn off grid
min = -1.5; % set y-min
max = 1.5; % set y-max
scrollWidth = 10; % display period in plot, plot entire data log if <= 0
delay = .01; % make sure sample faster than resolution
%Define Function Variables
time = 0;
data = 0;
count = 0;
%Set up Plot
plotGraph = plot(time,data,'-mo',...
'LineWidth',1,...
'MarkerEdgeColor','k',...
'MarkerFaceColor',[.49 1 .63],...
'MarkerSize',2);
title(plotTitle,'FontSize',25);
xlabel(xLabel,'FontSize',15);
ylabel(yLabel,'FontSize',15);
axis([0 10 min max]);
grid(plotGrid);
%Open Serial COM Port
s = serial(serialPort)
disp('Close Plot to End Session');
fopen(s);
tic
while ishandle(plotGraph) %Loop when Plot is Active
dat = fscanf(s,'%f'); %Read Data from Serial as Float
if(~isempty(dat) && isfloat(dat)) %Make sure Data Type is Correct
count = count + 1;
time(count) = toc; %Extract Elapsed Time
data(count) = dat(1); %Extract 1st Data Element
%Set Axis according to Scroll Width
if(scrollWidth > 0)
set(plotGraph,'XData',time(time > time(count)-scrollWidth),'YData',data(time > time(count)-scrollWidth));
axis([time(count)-scrollWidth time(count) min max]);
else
set(plotGraph,'XData',time,'YData',data);
axis([0 time(count) min max]);
end
%Allow MATLAB to Update Plot
pause(delay);
end
end
%Close Serial COM Port and Delete useless Variables
fclose(s);
clear count dat delay max min plotGraph plotGrid plotTitle s ...
scrollWidth serialPort xLabel yLabel;
disp('Session Terminated...');
The trick to get reliable plotting and manipulation is to always specify the parent explicitly using the Parent parameter when creating a plot or any other graphics object. All graphics objects support this parameter.
hax = axes();
plot(x,y, 'Parent', hax);
The other alternative, as suggested by #matlabgui is to specify the parent axes as the first input to plot:
plot(hax, x, y);
I personally prefer to use the Parent parameter as a parameter value pair though, as that behavior is consistent across all graphics objects.
You should also specify the axes handle when using other functions which operate on an axes.
xlabel(hax, 'XLabel')
ylabel(hax, 'YLabel')
title(hax, 'This is a title')
axis(hax, [0 0 1 1])
grid(hax, 'on')
hold(hax, 'on')
This is particularly important if you are dealing with an interactive GUI as the user could easily click on a different axes in the middle of your plotting causing the value of gca to change unexpectedly. Also changing the current axes (using axes(hax)) can cause a poor user experience.
Summary
For your specific code, this would involve changing your initial plot call:
plotGraph = plot(time,data,'-mo',...
'LineWidth',1,...
'MarkerEdgeColor','k',...
'MarkerFaceColor',[.49 1 .63],...
'MarkerSize',2, ...
'Parent', handles.axes2);
I would also recommend adding explicit axes handles to your calls to: grid, title, axis, xlabel, and ylabel to ensure that their target is the axes you want.