Related
Im trying to create a project in MATLAB where i project a heat map matrix on to a cylinder in MATLAB but i'm bumping in to all kinds of issues.
Im using MATLAB version R2019b(Latest version).
Now my first issue id like to adress is is the modells being absolutely tiny even when i zoom in to the max.
Is there any way to make these models larger or to display them in a separate window ??
Also my second question is the regarding the scaling. As you can see the scale on the Z-axis of the cylinder goes to 512. any way to get a larger more detailed image where i can see each point on that scale?
clear vars
filename =
['/Users/gomer/Documents/Datavisualisering/Projekt/data/day/filenames.txt'];
%This line simply gives us a table of all filenames in this file.
T = readtable(filename);
tsize = size(T);
%extracts the content of the table as a categorical array.
%%
%
% {rownumber,variablenumber}. {100,1} = row 100, variable 1.
%converts the categorical array into a string array.
%joins the string array across the column.
%string(T{100:105,1}); implies from row 100 to row 105 and use variable 1.
%This line simply adds the name of the file at row 100 to the path of the
%file. Hnece we get a full filepath.
filename = strcat('/Users/gomer/Documents/Datavisualisering/Projekt/data/day/', string(T{100,1}));
map100 = getHeatMap(filename);
%%
%
filename = strcat('/Users/gomer/Documents/Datavisualisering/Projekt/data/day/', string(T{1000,1}));
map1000 = getHeatMap(filename);
%creates a image
k=imshow(map100);
%creates a colormap.
%gca returns the current axes (or standalone visualization) in the current figure.
%hence the command just works top down and affects last image displayed.
colormap(gca, 'jet');
k=imshow(map1000);
colormap(gca, "jet");
function heat = getHeatMap(filename)
%Returns a struct with info about the file.
s = dir(filename);
%Opens a file for reading, hence the 'r'.
fin=fopen(filename,'r');
%A = fread(fileID,sizeA,precision)
%reads file data into an array, A, with dimensions, sizeA, and positions the file pointer after the last value read.
%fread populates A in column order.
I=fread(fin,s.bytes,'uint8=>uint8');
%The uint16 function converts a Input array, specified as a scalar, vector, matrix, or multidimensional array.
%Converts the values in to type uint16 and creates a Matrix with the values.
%Looks more like we are just calculating the size of values to be
%deducted from matrix size (no idea why).
w = uint16(I(1))+256*uint16(I(2));
h = uint16(I(3))+256*uint16(I(4));
skip = s.bytes - w*h + 1;
IN = I(skip:1:s.bytes);
%reshape(A,sz) reshapes A using the size vector, sz, to define size(B). For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix.
%sz must contain at least 2 elements, and prod(sz) must be the same as numel(A).
%single(X) converts the values in X to single precision.
Z=single(reshape(IN,w,h));
%Interpolate the values.
%telling the system which points to interpolate in between.
Z=griddedInterpolant(Z');
y_range = linspace(1.0,single(h),360);
x_range = linspace(1.0,single(w),512);
%Used to apecify the query points (points in between which we want
%interpolation) as vectors (this is to get a more continues image).
%specifies the query points as grid vectors.
%Use this syntax to conserve memory when you want to query a large grid of points.
heat = uint8(Z({y_range, x_range}));
end
Thank you
Resizing Figure Window
Copying your script to a .m and running it instead of a live .mlx file will automatically create all the figures in a separate window by default. To adjust the size of the figures the following the position property can be modified. To adjust the scale functions xticks(), yticks() and zticks() can be used. These three scale functions take in an array representing all the line markers along the respective axis/scale.
Test Plot Script:
X_Position = 10;
Y_Position = 10;
Width = 1000;
Height = 500;
%Configuring the figure settings%
figure('Position', [X_Position Y_Position Width Height])
%Test plot (replace with your plot)%
Data = [1 2 3 4 5 6];
plot(Data);
Plotting Heatmaps on a Cylindrical Surfaces
Method 1: Using warp() Function
Haven't delved into which orientation the data should be set as but this is an option to use the warp() function to wrap the heatmap around a cylinder. They're most likely other 3D plotting options if specific points are of interest. The points of the cylinder to be plotted are generated using the cylinder() function which returns the xyz-coordinates of the cylinder's wireframe. The fourth input argument into the warp() function serves and a colormap in this case it is proportional to the heatmap values.
load('HeatMapMatrix.mat');
%Setting up the figure%
clf;
close all;
figure('Position', [10 10 1000 500])
%Creating the cylinder%
Cylinder_Radius = 360;
Cylinder_Height = 512;
[X,Y,Z] = cylinder(Cylinder_Radius,Cylinder_Height-1);
%Warping the heatmap along the cylinder%
subplot(1,2,1); warp(X,Y,Cylinder_Height.*Z,map100');
colormap(gca,'jet');
subplot(1,2,2); warp(X,Y,Cylinder_Height.*Z,map100);
colormap(gca,'jet');
Method 2: Plotting All Points and Using surf() Function:
In this case, the coordinates for a cylinder are generated by first finding the coordinates of the circumference of the cylinder. This is done by using the sin() and cos() relationships:
X-Points = Radius × cos(𝜃)
Y-Points = Radius × sin(𝜃)
This results in the xy-coordinates of the cylinder's circle. These xy-coordinates need to be duplicated using repmat() to be later used for the varying heights. The process can be described best with a diagram as follows:
Four matrices above are created to plot each Heat Data point corresponding to an xyz-coordinate. The x and y coordinates are repeated in every row of matrices X-Points and Y_Points since those are constant for the repeating circles. The columns of the matrix Z-Points are also duplicates of each other since the heights should be constant for each row corresponding to each circle.
load('HeatMapMatrix.mat');
Radius = 20;
Number_Of_Data_Points = 360;
Theta = linspace(0,2*pi,Number_Of_Data_Points);
%The xy values according to radius and number of points%
X_Points = Radius*cos(Theta);
Y_Points = Radius*sin(Theta);
map100 = rot90(map100);
Sample_Range = 255 - 0;
Temperature_Range = 450 - 50;
Multiplier = Temperature_Range/Sample_Range;
map100 = map100.*Multiplier + 50;
Height = 512;
X_Points = repmat(X_Points,Height,1);
Y_Points = repmat(Y_Points,Height,1);
Z_Points = (1:512)';
Z_Points = repmat(Z_Points,1,Number_Of_Data_Points);
clf;
close;
figure('Position', [10 10 800 500])
Offset = 200;
subplot(1,3,1:2); Surface = surf(Y_Points,X_Points,Z_Points,'Cdata',map100);
title("3D Heatmap Plot");
zlabel("Height");
shading interp
colorbar
% direction = [0 1 0];
% rotate(Surface,direction,90)
Maximum_Value = 450;
Minimum_Value = 50;
caxis([Minimum_Value Maximum_Value]);
subplot(1,3,3); imshow(rot90(rot90(map100)));
colormap(gca, 'default');
title("Flat Heatmap Plot");
caxis([Minimum_Value Maximum_Value]);
colorbar;
Ran using MATLAB R2019b
I have a spectral data (1000 variables on xaxis, and peak intensities as y) and a list of peaks of interest at various specific x locations (a matrix called Peak) which I obtained from a function I made. Here, I would like to draw a line from the maximum value of each peaks to the xaxis - or, eventually, place a vertical arrow above each peaks but I read it is quite troublesome, so just a vertical line is welcome. However, using the following code, I get "Error using line Value must be a vector of numeric type". Any thoughts?
X = spectra;
[Peak,intensity]=PeakDetection(X);
nrow = length(Peak);
Peak2=Peak; % to put inside the real xaxis value
plot(xaxis,X);
hold on
for i = 1 : nbrow
Peak2(:,i) = round(xaxis(:,i)); % to get the real xaxis value and round it
xline = Peak2(:,i);
line('XData',xline,'YData',X,'Color','red','LineWidth',2);
end
hold off
Simple annotation:
Here is a simple way to annotate the peaks:
plot(x,y,x_peak,y_peak+0.1,'v','MarkerFaceColor','r');
where x and y is your data, and x_peak and y_peak is the coordinates of the peaks you want to annotate. The add of 0.1 is just for a better placing of the annotation and should be calibrated for your data.
For example (with some arbitrary data):
x = 1:1000;
y = sin(0.01*x).*cos(0.05*x);
[y_peak,x_peak] = PeakDetection(y); % this is just a sketch based on your code...
plot(x,y,x_peak,y_peak+0.1,'v','MarkerFaceColor','r');
the result:
Line annotation:
This is just a little bit more complicated because we need 4 values for each line. Again, assuming x_peak and y_peak as before:
plot(x,y);
hold on
ax = gca;
ymin = ax.YLim(1);
plot([x_peak;x_peak],[ymin*ones(1,numel(y_peak));y_peak],'r')
% you could write instead:
% line([x_peak;x_peak],[ymin*ones(1,numel(y_peak));y_peak],'Color','r')
% but I prefer the PLOT function.
hold off
and the result:
Arrow annotation:
If you really want those arrows, then you need to first convert the peak location to the normalized figure units. Here how to do that:
plot(x,y);
ylim([-1.5 1.5]) % only for a better look of the arrows
peaks = [x_peak.' y_peak.'];
ax = gca;
% This prat converts the axis unites to the figure normalized unites
% AX is a handle to the figure
% PEAKS is a n-by-2 matrix, where the first column is the x values and the
% second is the y values
pos = ax.Position;
% NORMPEAKS is a matrix in the same size of PEAKS, but with all the values
% converted to normalized units
normpx = pos(3)*((peaks(:,1)-ax.XLim(1))./range(ax.XLim))+ pos(1);
normpy = pos(4)*((peaks(:,2)-ax.YLim(1))./range(ax.YLim))+ pos(2);
normpeaks = [normpx normpy];
for k = 1:size(normpeaks,1)
annotation('arrow',[normpeaks(k,1) normpeaks(k,1)],...
[normpeaks(k,2)+0.1 normpeaks(k,2)],...
'Color','red','LineWidth',2)
end
and the result:
I am trying to plot a hypnogram (graph that shows sleep cycles) and am currently using stairstep function to plot it. Below is a sample data since the one I am working with is huge:
X = linspace(0,4*pi,10);
Y = sin(X);
stairs(X,Y)
How do I make the lines of every ticks/score on the y-axis have a unique color? Which looks something like this:
One way to do it would be to segregate your data into as many dataset as your have flat levels, then plot all these data sets with the required properties.
There is however a way to keep the original dataset into one piece. If we consider your initial example data:
X = linspace(0,4*pi,10);
Y = sin(X);
step 1: recreate a "stair" like data set
Then by recombining the elements of X and Y we can obtain the exact same output than with the stairs function:
x = reshape( [X;X], 1,[] ); x(1) = [] ; % duplicate each element, remove the first one
y = reshape( [Y;Y], 1,[] ); y(end) = [] ; % duplicate each element, remove the lastone
hp = plot(x,y) ;
step 2: Use patch to be able to specify level colors
The patch object has many option for colouring faces, vertex and edges. The default patch object will try to close any profile given in coordinate by joining the first and last point. To override this behaviour, you just need to add a NaN element to the end of the coordinate set and patch will produce a simple line (but all the colouring options remain !).
To determine how many levels and how many colors we will need, we use the function unique. This will tell us how many unique levels exist in the data, and also we can associate each level with an index which will point to the color map.
%% Basic level colored line patch
% create profile for patch object
x = reshape([X;X],1,[]); x(1) = [] ; % same as above to get a "stairs" shape
y = reshape([Y;Y],1,[]); y(end) = [] ; % idem
xp = [x,NaN] ; % add NaN in last position so the patch does not close the profile
yp = [y,NaN]; % idem
% prepare colour informations
[uy,~,colidx] = unique(Y) ;
ncolor = length(uy) ; % Number of unique level
colormap(hsv(ncolor)) % assign a colormap with this number of color
% create the color matrix wich will be sent to the patch object
% same method of interleaving than for the X and Y coordinates
cd = reshape([colidx.';colidx.'],1,[]);
hp = patch(xp,yp,cd,'EdgeColor','interp','LineWidth',2) ;
colorbar
Yes! ... now our flat levels have a colour corresponding to them ... but wait, those pesky vertical lines are still there and polluting the graph. Could we colour them in a different way? Unfortunately no. No worries however, there is still a way to make them completely disappear ...
step 3: Use NaN to disable some segments
Those NaN will come to the rescue again. Any segment defined with a NaN will not be plotted by graphic functions (be it plot, patch, surf or any other ...). So what we can do is again interleave some NaN in the original coordinate set so only the horizontal lines will be rendered. Once the patch is created, we can build a second, "opposite", coordinate set where only the vertical lines are visible. For this second set, since we do not need fancy colouring, we can simply render them with plot (but you could also build a specific patch for that too if you wanted to colour them differently).
%% invisible vertical line patch + dashed vertical lines
% prepare profile points, interleaving NaN between each pair
vnan = NaN(size(X)) ;
xp = reshape([X;vnan;X],1,[]); xp([1:2 end]) = [] ;
yp = reshape([Y;Y;vnan],1,[]); yp(end-2:end) = [] ;
% prepare the vertical lines, same method but we interleave the NaN at one
% element offset
xv = reshape([X;X;vnan],1,[]); xv([1:3 end]) = [] ;
yv = reshape([Y;vnan;Y],1,[]); yv([1:2 end-1:end]) = [] ;
% prepare colormap and color matrix (same method than above)
[uy,~,colidx] = unique(Y) ;
ncolor = length(uy) ; % Number of unique level
colormap(hsv(ncolor)) % assign a colormap with this number of color
% create the color matrix wich will be sent to the patch object
% same method of interleaving than for the X and Y coordinates
cd = reshape([colidx.';colidx.';vnan],1,[]); cd(end-2:end) = [] ;
% draw the patch (without vertical lines)
hp = patch(xp,yp,cd,'EdgeColor','flat','LineWidth',2) ;
% add the vertical dotted lines
hold on
hv = plot(xv,yv,':k') ;
% add a label centered colorbar
colorbar('Ticks',((1:ncolor)+.5)*ncolor/(ncolor+1),'TickLabels',sprintf('level %02d\n',1:ncolor))
I have used the hsv colormap in the last example because your example seems to indicate that you do not need gradually progressing colors. You could also define a custom colormap with the exact color you want for each level (but that would be another topic, already covered many time if you search for it on Stack Overflow).
Happy R.E.M. sleeping !
Below code is not that efficient, but works well.
Basically, it draws line by line from left to right.
Firstly, generate sample data
num_stage = 6;
% generate sample point
x = linspace(0,1,1000)';
% generate its stage
y = round((sin(pi*x)+1)*(num_stage-1)/2)/(num_stage-1);
stage = unique(y); % find value of each stage
color_sample = rand(num_stage,3); % set color sample
Then we can draw like this
idx = find([1;diff(y)]); % find stage change
idx(end+1) = length(x)+1; % add last point
% display routine
figure;
% left end stage
k = 1;
% find current stage level
c = find(stage == y(idx(k)));
% plot bold line
plot(x([idx(k),idx(k+1)-1]),y(idx(k))*ones(2,1),'color',color_sample(c,:),'linewidth',5);
hold on;
for k = 2 : length(idx)-1
% find current stage level
c = find(stage == y(idx(k)));
% plot dashed line from left stage to current stage
plot(x([idx(k)-1,idx(k)]),[y(idx(k-1));y(idx(k))],'--','color',[0.7,0.7,0.7]);
% plot bold line for current stage with specified color
plot(x([idx(k),idx(k+1)-1]),y(idx(k))*ones(2,1),'color',color_sample(c,:),'linewidth',5);
end
% set x-axis
set(gca,'xlim',[x(1),x(end)]);
Following is result
Use if statement and divide it blocks. Check the criteria of Y-axis to be in a certain range and if it falls in that range, plot it there using the colors you want. For example if (y>1) plot(x,y,'r') else if (y some range) plot(x,y,'b'). Hope it helps
I have opened a highly complex .fig figure from file in matlab with openfig.
After this I have cropped the figure with
axis([X1, X2, Y1, Y2])
I now want save the cropped figure so that it is of a reduced size when saved. The problem is that savefig will save the complete image zoomed to the axis specified. How can I save the figure, permanently cropped to the axis I have specified? e.g. it should not be possible to zoom out when opening the new image.
I don't have MATLAB in front of me, and I don't have your data to test this with, so this is an approximate answer, but as #natan mentions in the comments above, you can harvest the data from the figure, which is stored in 'XData' and 'YData'. You can then crop the data to just the parts you want and then replace the existing data with the cropped data. It will end up looking something like this:
kids = findobj(gca,'Type','line');
K = length(kids);
Xrange = get(gca,'XLim');
Yrange = get(gca,'YLim');
for k = 1:K
X = get(kids(k),'XData');
Y = get(kids(k),'YData');
idx = X >= min(Xrange) & X <= max(Xrange) & Y >= min(Yrange) & Y <= max(Yrange);
set(kids(k),'XDATA',X(idx),'YDATA',Y(idx));
end
You'll have to modify this if your plots have patch objects, bar objects, etc., but the idea is there.
Edge cases:
There are a few edge cases to consider as #Jan has rightly pointed out. The first is that the approach above assumes a rather high density of points even in the expanded scales and will leave a small gap between the end of the line and the axes. For low-point-density lines, you need to expand the idx variable to capture the next point outside the axes in either direction:
idx_center = X >= min(Xrange) & X <= max(Xrange) & Y >= min(Yrange) & Y <= max(Yrange);
idx_plus = [false idx(1:end-1)];
idx_minus = [idx(2:end) false];
idx = idx_center | idx_plus | idx_minus;
That will only expand the number of points if there is at least one point inside the window. The other edge case is where the line passes through the window but does not contain any points inside the window, which would be the case if idx is all false. In that case, you need the largest point outside the left axis and the smallest point outside the right axis. If either of these searches come up empty, then the line doesn't pass through the window and can be discarded.
if ~any(idx)
idx_low = find(X < min(Xrange),1,'last');
idx_high = find(X > max(Xrange),1,'first');
if isempty(idx_low) | isempty(idx_high)
% if there aren't points outside either side of the axes then the line doesn't pass through
idx = false(size(X));
else
idx = idx_low:idx_high;
end
end
This doesn't test whether the line is inside the y-bounds, so it may be possible that the line will pass above or below the window without intersecting. If that is important you will need to test the line connecting the found points. An extra 2 points in memory should not be a big deal. If it is an issue, then I leave it as an exercise to the student to work out the test of whether a line passes through the axes.
Putting it all together:
kids = findobj(gca,'Type','line'); % find children of the axes that are lines
K = length(kids); % count them
Xrange = get(gca,'XLim'); % get the axis limits
Yrange = get(gca,'YLim');
for k = 1:K
X = get(kids(k),'XData'); % pull the x-y data for the line
Y = get(kids(k),'YData');
% find the points inside the window and then dilate the window by one in
% each direction
idx_center = X >= min(Xrange) & X <= max(Xrange) & Y >= min(Yrange) & Y <= max(Yrange);
idx_plus = [false idx(1:end-1)];
idx_minus = [idx(2:end) false];
idx = idx_center | idx_plus | idx_minus;
% handle the edge case where there are no points in the window but the line still passes through
if ~any(idx)
idx_low = find(X < min(Xrange),1,'last');
idx_high = find(X > max(Xrange),1,'first');
if isempty(idx_low) | isempty(idx_high)
% if there aren't points outside either side of the axes then the line doesn't pass
% through
idx = false(size(X));
else
% numerical indexing instead of logical, but it all works the same
idx = idx_low:idx_high;
end
end
if any(idx)
% reset the line with just the desired data
set(kids(k),'XDATA',X(idx),'YDATA',Y(idx));
else
% if there still aren't points in the window, remove the object from the figure
delete(kids(k));
end
end
Hi everyone I want to find all the points from a plot and save it in array
for example I've this graph I want all the point from the beginning of the line to the end of it
% Drawing a Trajectory
prompt={'Enter The Number Of Lines:'}; % Enter statements at the Command Window to accept input from you.
title='Draw Line '; % Name the Command Window
n=inputdlg(prompt); % Create and open input dialog box
A = sscanf(n{1}, '%d'); % Convert from String to Int
[x,y] = ginput(A); % Graphical input from mouse or cursor
plot(x,y)
posth = [x,y]; % Save 'x' and 'y' as Array
If you want to obtain x and y with only the plot after the fact, in this case you can do:
line_handles = get(gca,'Children');
x = get(line_handles,'XData');
y = get(line_handles,'YData');
where gca refers to the current axis of the current figure (you can replace it with the handle, h, of the plot, i.e., change your code to h = plot(x,y)). If there is only one line, x and y will be vectors. If there are multiple lines, they will be cell arrays.
You can also output x and y simultaneously as a cell array via:
xy = get(get(gca,'Children'),{'XData','YData'});
where
x = xy{1,:};
y = xy{2,:};