Hold on only the axis, not the data - matlab

I want my graph to fixed axes and also plot the data one by one. Everything is already known, however if i use hold off to remove the first set of data, it also forgets the limits on the axes and automatically assigns new limits for the second set of data.
Is it somehow possible to keep the axes the same for each time a separate data piece is plotted in the same figure?
code for now is:
figure(4)
grid on
axis([xL yL zL])
for j = 1:n % n is amount of data sets
for i = 1:2 % two items drawn per data set
*plot data*
hold on
end
%This part has to be done every iteration again in order to make it work now
axis([xL yL zL])
xlabel = ...
ylabel
zlabel
title
pause(tstop)
hold off
end
after some searching the only relevant topic i found was; Matlab: Plot a subplot with hold on and hold off in a loop without always calling xlabel, ylabel, xlim, etc
However i do not understand it at all. It uses a parent figure, replacechildren, nextplot and such which i am not familiar with and also cant find much information about.

Here's an example that can be easily adapted to your needs:
xlim([0 10]) %// set x-axis limits
ylim([0 10]) %// set y-axis limits
set(gca,'nextplot','replacechildren') %// prevent axis limits from changing with
%// each new plot
plot(3:8,3:8); %// note axis limits are kept as [0 10]
pause(1)
plot(5:7,5:7); %// note axis limits are kept as [0 10]

Related

How to merge different plot but same y axis in matlab

I'm always see this kind of graph in XRD plot:
and i'm wondering how they do that?, if you have different XRD plot and assuming having the same y axis, can matlab do this? thanks.
Here is a way to do it.You can customize it as you want, but this should hopefully get you going.
First create an axes and change its position/size inside the figure, shifting it upward to make room for the 2nd axes as well as removing the x and y labels that you don't want. Then create a 2nd axes with specified position/size to make it fit below the 1st one.
Sample code:
clear
clc
%// Generate dummy data
x = 1:2:100;
y1 = rand(1,numel(x));
figure;
%// Make an axes and set its position
haxes1 = axes('Position',[.1 .1 .8 .7],'Color',[1 1 1])
%// Plot 1st curve
plot(x,y1,'Parent',haxes1)
%// Remove box and labels
box off
set(gca,'XTickLabel','','XTick',[],'YTick',[])
hold on
%// Get current axes position. You set it so you could get the parameters
%// directly as well.
axes1Pos = get(gca,'Position');
%// Shift 1st axes upward
set(gca,'Position',[axes1Pos(1) 2.6*axes1Pos(2) axes1Pos(3) axes1Pos(4)])
%// Change the poisition/size of the 2nd axes to fit below the 1st one
haxes2 = axes('Position',[axes1Pos(1) axes1Pos(2)/2.5 axes1Pos(3) axes1Pos(4)/2.5]) ;
%// Use linspace to generate colored points to use with scatter.
c = linspace(1,10,length(x));
%// Add 2nd plot and keep only x label
scatter(x,rand(1,numel(x)),40,c,'filled')
set(gca,'YTick',[])
box off
%// Place a ylabel for both axes
text(-4, 1.7,'Super nice y label','rotation',90,'FontSize',16,'HorizontalAlignment','center')
Sample output:
There are other ways to do this as well.
Hope that helps!

How to get variable scales on y axis for same graph in matlab plotting?

I am working on matlab programming, my problem is that in the same graph on y axis i need to have variable scaling, for example from 0.1 to 1 i need to have a gap between scales 0.1, but after 1 I need to have scale gap of 2, is there some command available for the same?
There is an example by The Mathworks on Matlab answers which does pretty much what you want to achieve. The idea is to create 2 axes on the same figure and use one axes to plot some data (eg. for the 0.1:0.1:1 tick marks) and the rest on the other axes. Then you overlay both axes with a transparent background:
%Create two overlapping axes
axes_handle_1 = axes;
axes_position = get(axes_handle_1, 'Position');
axes_handle_2 = axes('Position', axes_position);
%Create some data with a large gap in the x domain
my_x_data = [1:10 25:35];
my_y_data = rand(1, length(my_x_data));
%Plot the two sections of data on different axes objects
plot(axes_handle_1, my_x_data(1:10), my_y_data(1:10))
plot(axes_handle_2, my_x_data(11:end), my_y_data(11:end))
%Link the y axis limits and fontsize property of the axes objects
linkaxes([axes_handle_1 axes_handle_2], 'y');
linkprop([axes_handle_1 axes_handle_2], 'FontSize');
%Set the x range limits and tick mark positions of the first axes object
set(axes_handle_1, 'XLim', [1 21], ...
'XTick', [1 5 10])
%Set the x range limits and tick mark positions for the second axes object.
%Also set the background color to 'none', which makes the background
%transparent.
set(axes_handle_2, 'Color', 'none', ...
'YTickLabel', [], ...
'XLim', [14 35], ...
'XTick', [25 30 35])
It's quite straightforward and to my knowledge there is no built-in way to do it otherwise, except maybe with submissions from the File Exchange. Anyhow if you have questions about the above code please ask!
Please use gca property of matlab. In gca you can set a variable as your scales. Make that variable by merging two different scales
x=[1:80];
y=[.1:.1:8];
figure
plot(x,y);
%First Scale
scale1=[.1:.1:1];
%New scale is being started from 3. If we start from 1, 1 will be repeated
scale2=[3:2:9];
%Merging two variables scale1 and scale2
set(gca,'YTick',[scale1 scale2]);
Please refer http://www.mathworks.in/help/matlab/creating_plots/change-tick-marks-and-tick-labels-of-graph.html
You can also try the idea of scaling one dataset so that it has a similar magnitude as the other data set. Here you can multiply one dataset by 100 (or any suitable scaling parameter), and then it will be similar in size to the other data set. In order to clearly mention which data has been scaled in the graph use the legend.
plot(x,data1,x,100*data2)
legend('data1','100*data2','location','southeast')
Hope this helps.

How to make 1-D plots in MATLAB?

How can I make plots in MATLAB like in below?
I won't need labels, so you can ignore them. I tried using normal 2D plot, by giving 0 to y parameter for each data points. It does help, but most of the plot remains empty/white and I don't want that.
How can I solve this problem?
Edit:
This is how I plot(playing with values of ylim does not help):
hold on
for i=1:120
if genders(v_labels(i)) == CLASS_WOMAN
plot(v_images_lda(i,:) * w_lda,0,'r*');
else
plot(v_images_lda(i,:) * w_lda,0,'b.');
end
end
title('LDA 1D Plot');
ylim([-0.2 0.2]);
hold off
One way to do this would be to adjust the 'XLim', 'YLim', and 'DataAspectRatio' properties of the axes so that it renders as essentially a single line. Here's an example:
data1 = rand(1,20)./2; %# Sample data set 1
data2 = 0.3+rand(1,20)./2; %# Sample data set 2
hAxes = axes('NextPlot','add',... %# Add subsequent plots to the axes,
'DataAspectRatio',[1 1 1],... %# match the scaling of each axis,
'XLim',[0 1],... %# set the x axis limit,
'YLim',[0 eps],... %# set the y axis limit (tiny!),
'Color','none'); %# and don't use a background color
plot(data1,0,'r*','MarkerSize',10); %# Plot data set 1
plot(data2,0,'b.','MarkerSize',10); %# Plot data set 2
And you will get the following plot:
Here's one way to reproduce your figure using dsxy2figxy and annotate. dsxy2figxy can be hard to find the first time, as it is not really in your path. It is part of the MATLAB package and is provided in the example functions. You can reach it by searching for it in the help docs and once you find it, open it and save it to a folder in your path.
h1=figure(1);clf
subplot(4,1,1);
hold on
xlim([0.2,1]);ylim([-1,1])
%arrow
[arrowX,arrowY]=dsxy2figxy([0.2,1],[0,0]);
annotation('arrow',arrowX,arrowY)
%crosses
x=[0.3,0.4,0.6,0.7,0.75];
plot(x,0,'kx','markersize',10)
%pipes
p=[0.5,0.65];
text(p,[0,0],'$$\vert$$','interpreter','latex')
%text
text([0.25,0.5,0.65],[1,-1,-1]/2,{'$$d_i$$','E[d]','$$\theta$$'},'interpreter','latex')
axis off
print('-depsc','arrowFigure')
This will produce the following figure:
This is sort of a hackish way to do it, as I've tricked MATLAB into printing just one subplot. All rasterized formats (jpeg, png, etc) will not give you the same result, as they'll all print the entire figure including where the non-declared subplots should've been. So to get this effect, it has to be an eps, and it works with it because eps uses much tighter bounding boxes... so all the meaningless whitespace is trimmed. You can then convert this to any other format you want.
Ok so the closest I have come to solving this is the following
hax = gca();
hold on
for i=1:120
if genders(v_labels(i)) == CLASS_WOMAN
plot(v_images_lda(i,:) * w_lda,0,'r*');
else
plot(v_images_lda(i,:) * w_lda,0,'b.');
end
end
set(hax, 'visible', 'off');
hax2 = axes();
set(hax2, 'color', 'none', 'ytick', [], 'ycolor', get(gcf, 'color');
pos = get(hax, 'position');
set(hax2, 'position', [pos(1), pos(2)+0.5*pos(4), pos(3), 0.5*pos(4)]);
title('LDA 1D Plot');
hold off
So in short, I hid the original axis and created a new one located at 0 of the original axis, and as I couldn't remove the y axis completely I set it's color to the background color of the figure.
You can then decide if you also want to play with the tick marks of the x-axis.
Hope this helps!
Very naive trick but a useful one.
Plot in 2d using matlab plot function. Then using edit figure properties compress it to whichever axis you need a 1D plot on !! Hope that helps :)

Matlab: Plot a subplot with hold on and hold off in a loop without always calling xlabel, ylabel, xlim, etc

Matlab question: this might be really simple but I can't figure it out...I'm pretty new. I have a plot window, broken up into two subplots, lets call them A and B, which have different labels and limits. I (hold on), make several plots to B, then I (hold off), then start iterating. In the loop, I want to update both A and B with NEW plots, but I want the axis labels, and xlim and ylim to stay the same, WITHOUT having to call xlabel, xlim, etc every iteration.
Now, (hold off) destroys all axis properties. How do I save the axis properties so I don't have to keep calling xlabel, etc in the loop? I've tried newplot, setting the Nextplot property, etc to no avail. I'd like a simple solution please...not something like re-writing the plot command. Thanks!
hfig=figure();
hax = axes('Parent',hfig);
plot(hax,x,y);
hold on
plot(hax,x1,y1);
%this hold off resets the axes
hold off
while (1)
subplot('Position',[.07 .05 .92 .44]);
%I want to do this without having to call xlabel, ylabel, etc
%over and over
plot(newx, newy);
xlabel()
ylabel()
hold on
plot(newx1, newx2)
hold off
...
end
One solution here is to initialize your plot and axes properties before your loop, then within your loop set the 'NextPlot' property of the axes to 'replacechildren' so that only the plot objects (and not the axes settings) will be changed on the next call to PLOT:
hFigure = figure();
hAxes = axes('Parent',hFigure);
plot(hAxes,x,y);
hold on;
plot(hAxes,x1,y1);
xlabel(...); %# Set the x label
ylabel(...); %# Set the y label
xlim([...]); %# Set the x limits
ylim([...]); %# Set the y limits
while (1)
set(hAxes,'NextPlot','replacechildren');
plot(hAxes,newx,newy);
hold on;
plot(hAxes,newx1,newx2);
...
end
This should maintain the settings for hAxes when new data is plotted in the loop.

Matlab axes scaling

how exactly do you get fixed scaling of axes in Matlab plot when plotting inside a loop? My aim is to see how data is evolving inside the loop. I tried using axis manual and axis(...) with no luck. Any suggestions?
I know hold on does the trick, but I don't want to see the old data.
If you want to see your new plotted data replace the old plotted data, but maintain the same axes limits, you can update the x and y values of the plotted data using the SET command within your loop. Here's a simple example:
hAxes = axes; %# Create a set of axes
hData = plot(hAxes,nan,nan,'*'); %# Initialize a plot object (NaN values will
%# keep it from being displayed for now)
axis(hAxes,[0 2 0 4]); %# Fix your axes limits, with x going from 0
%# to 2 and y going from 0 to 4
for iLoop = 1:200 %# Loop 100 times
set(hData,'XData',2*rand,... %# Set the XData and YData of your plot object
'YData',4*rand); %# to random values in the axes range
drawnow %# Force the graphics to update
end
When you run the above, you will see an asterisk jump around in the axes for a couple of seconds, but the axes limits will stay fixed. You don't have to use the HOLD command because you are just updating an existing plot object, not adding a new one. Even if the new data extends beyond the axes limits, the limits will not change.
You have to set the axes limits; ideally you do that before starting the loop.
This won't work
x=1:10;y=ones(size(x)); %# create some data
figure,hold on,ah=gca; %# make figure, set hold state to on
for i=1:5,
%# use plot with axis handle
%# so that it always plots into the right figure
plot(ah,x+i,y*i);
end
This will work
x=1:10;y=ones(size(x)); %# create some data
figure,hold on,ah=gca; %# make figure, set hold state to on
xlim([0,10]),ylim([0,6]) %# set the limits before you start plotting
for i=1:5,
%# use plot with axis handle
%# so that it always plots into the right figure
plot(ah,x+i,y*i);
end