How to make 1-D plots in MATLAB? - 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 :)

Related

Hold on only the axis, not the data

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]

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 specify the axis size when plotting figures in Matlab?

Suppose that I have 2 figures in MATLAB both of which plot data of size (512x512), however one figure is being plotted by an external program which is sets the axis parameters. The other is being plotted by me (using imagesc). Currently the figures, or rather, the axes are different sizes and my question is, how do I make them equal?.
The reason for my question, is that I would like to export them to pdf format for inclusion in a latex document, and I would like to have them be the same size without further processing.
Thanks in Advance, N
Edit: link to figures
figure 1: (big)
link to smaller figure (i.e. the one whose properties I would like to copy and apply to figure 1)
For this purpose use linkaxes():
% Load some data included with MATLAB
load clown
% Plot a histogram in the first subplot
figure
ax(1) = subplot(211);
hist(X(:),100)
% Create second subplot
ax(2) = subplot(212);
Now link the axes of the two subplots:
linkaxes(ax)
By plotting on the second subplot, the first one will adapt
imagesc(X)
First, you have the following:
Then:
Extending the example to images only:
load clown
figure
imagesc(X)
h(1) = gca;
I = imread('eight.tif');
figure
imagesc(I)
h(2) = gca;
Note that the configurations of the the first handle prevail:
linkaxes(h)
1.Get the handle of your figure and the axes, like this:
%perhaps the easiest way, if you have just this one figure:
myFigHandle=gcf;
myAxHandle=gca;
%if not possible, you have to search for the handles:
myFigHandle=findobj('PropertyName',PropertyValue,...)
%you have to know some property to identify it of course...
%same for the axes!
2.Set the properties, like this:
%set units to pixels (or whatever you prefer to make it easier to compare to the other plot)
set(myFigHandle, 'Units','pixels')
set(myAxHandle, 'Units','pixels')
%set the size:
set(myFigHandle,'Position',[x_0 y_0 width height]) %coordinates on screen!
%set the size of the axes:
set(myAxHandle,'Position',[x_0 y_0 width height]) %coordinates within the figure!
Ok, based on the answer of #Lucius Domitius Ahenoba here is what I came up with:
hgload('fig1.fig'); % figure whose axis properties I would like to copy
hgload('fig2.fig');
figHandles = get(0,'Children');
figHandles = sort(figHandles,1);
ax(1) = findobj(figHandles(1),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
ax(2) = findobj(figHandles(2),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
screen_pos1 = get(figHandles(1),'Position');
axis_pos1 = get(ax(1),'Position');
set(figHandles(2),'Position',screen_pos1);
set(ax(2),'Position',axis_pos1);
This is the 'before' result:
and this is the 'after' result:
Almost correct, except that the aspect ratios are still off. Does anybody know how to equalize everything related to the axes? (I realize that I'm not supposed to ask questions when posting answers, however adding the above as a comment was proving a little unwieldy!)

Matlab: Plot3 not showing the 3rd axis

All the three variables I am using to plot are matrix of size 1x1x100. I am using this code line to plot:
hold on;
for i=1:100
plot3(R_L(:,:,i),N_Pc(:,:,i),CO2_molefraction_top_of_window(:,:,i),'o');
xlabel('R_L');
ylabel('N_P_c');
zlabel('CO_2')
end
However, I am not getting the third axis, and hence the third variable CO2_molefraction_top_of_window on the plot. May I know where am I wrong?
Besides the above question, but on the same subject, I want to know if there is any option where I can plot 4 dimensional plot just like the 3 dimensional plot which can be drawn using plot3?
So I had the same problem when using plot3. For some reason, using the hold on command "flattens" the plot. I'm not sure why, but I suspect it has something to do with the operation hold on performs on the plot.
Edit: To clarify, the 3d plot is still there, but the perspective has been forced to change. If you use the "rotate 3D" tool (the one with an arrow around a cube), you can see the graph is 3d, the default perspective is just straight on so only two axes are visible and it appears flat.
Just a note --- you only need to do the xlabel ylabel zlabel commands once (outside the loop).
Also:
is there any reason your matrices are 1x1x100 instead of just 100x1 or 1x100?
Because if you reshape them to 2D you can just do the plotting in one hit.
What do you mean by "missing third axis"? When I run your code (or as close as I can get, since you didn't provide a reproducible example), I do get a 3rd axis:
.
X = rand(1,1,100); % 1x1x100 X matrix
Y = rand(1,1,100); % 1x1x100 Y matrix
Z = rand(1,1,100); % 1x1x100 Z matrix
% Now, we could do a for loop and plot X(:,:,i), Y(:,:,i), Z(:,:,i),
% OR we can just convert the matrix to a vector (since it's 1x1x100 anyway)
% and do the plotting in one go using 'squeeze' (see 'help squeeze').
% squeeze(X) converts it from 1x1x100 (3D matrix) to 100x1 (vector):
plot3(squeeze(X),squeeze(Y),squeeze(Z),'o')
xlabel('x')
ylabel('y')
zlabel('z')
This gives the following, in which you can clearly see three axes:
If it's the gridlines that you want to make the graph look "more 3D", then try grid on (which is in the examples in the Matlab help file for plot3, try help plot3 from the Matlab prompt):
grid on
You will have to clarify "missing third axis" a bit more.
I came across a similar problem and as #Drofdarb's the hold on seems to flatten out one axis. Here is a snippet of my code, hope this helps.
for iter = 1:num_iters:
% hold on;
grid on;
plot3(tita0,tita1, num_iters,'o')
title('Tita0, Tita1')
xlabel('Tita0')
ylabel('Tita1')
zlabel('Iterations')
hold on; % <---- Place here
drawnow
end
As opposed to:
for iter = 1:num_iters:
grid on;
hold on; % <---- Not here
plot3(tita0,tita1, num_iters,'o')
title('Tita0, Tita1')
xlabel('Tita0')
ylabel('Tita1')
zlabel('Iterations')
% hold on;
drawnow
end

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