Labeling 3D Surface Plots in MATLAB along respective axes - matlab

I have doubts regarding Labeling 3D Surface Plots in MATLAB along respective axes.
for j=1:length(op)
x = op{j}(:,1);
z = st:inc:en;
y = op{j}(:,2:end);
figure
surf(x,z,y.','FaceAlpha',1.0) % surface plot
xlabel('Non-Dimensional Number (k_0a)')
ylabel('Non-Dimensional Horizontal Force (HF_P)')
zlabel('Non-Dimensional Porous Parameter (G_S)')
axis tight
view(30,40)
grid on
end
The result is the following 3D plot having labels not alligned in respective axis. Any help on alligning the labels in respective axes is highly appreciated.
Many Thanks.

You can set the position and the rotation of the label as follow,
[x,y] = meshgrid(1:0.5:10,1:20);
z = sin(x) + cos(y);
figure
surf(x,y,z,'FaceAlpha',1.0) % surface plot
xlabel('Non-Dimensional Number (k_0a)','FontSize', 20)
ylabel('Non-Dimensional Horizontal Force (HF_P)','FontSize', 20)
zlabel('Non-Dimensional Porous Parameter (G_S)','FontSize', 20)
axis tight
view(30,40)
grid on
xh = get(gca,'XLabel'); % Handle of the x label
set(xh, 'Units', 'Normalized')
pos = get(xh, 'Position');
set(xh, 'Position',pos.*[1,-0.5,1],'Rotation',-10)
yh = get(gca,'YLabel'); % Handle of the y label
set(yh, 'Units', 'Normalized')
pos = get(yh, 'Position');
set(yh, 'Position',pos.*[1,-0.7,1],'Rotation',30)
the results,
Ref

Related

How to format graph so that border starts at max x and y and how to replace a plot command

I am trying to format my graph so that the border ends at the max x and max y so there is not extra space between them and the border. Also, I'm trying to completely replace my first plot command with my second one. Should I just delete my first plot? Currently, the second plot goes over my first plot, removing most of my formatting.
clear all, close all
%%command to clear all variables and log history
x = linspace(-pi, pi, 200);
%creating x variable between - pi and 200 with pi distance between each
%value
y = sin(x) + cos(x);
%Creating y varable with the help of x
figure
plot(x,y)
title('2-D Plot')
xlabel('Theta (in radians)')
ylabel('Function Y')
xlim([-pi pi])
ylim([-1.414 1.414])
grid
plot(x,y,'r--')
grid
To fit the axes box tightly around the data without manually adjusting the axis limits, use:
axis tight;
and instead of re-plotting, you can update the relevant properties of the line.
x = linspace(-pi, pi, 200);
y = sin(x) + cos(x);
figure;
h = plot(x,y); %handle for the line plot
title('2-D Plot');
xlabel('Theta (in radians)');
ylabel('Function Y');
grid;
axis tight; %to set the axis limits equal to the range of the data
set(h, 'LineStyle', '--', 'Color', 'r'); %Updating the plot with required changes

matlab: moving circle along a graph and axis equal

Hello and pardon me if my english is a bit rusty. I'm trying to create a circle that moves along a parametric function (coordinates are stored in vectors). I have written a function for drawing the circle and I know that you can use the axis equal command in matlab in order to create a circle shape and avoid an ellipse. My problem is that when I do this the figure window becomes very wide relative to the plotted graph. Any input is appreciated.
MAIN CODE:
t = linspace(0,3);
x = 30*cos(pi/4)/2*(1-exp(-0.5*t));
y = (30*sin(pi/4)/2 + 9.81/0.5^2)*(1-exp(0.5*t)) - 9.81*t/0.5;
for i = 1:length(t)
plot(x,y)
axis equal
hold on
cirkel(x(i),y(i),1,1,'r') % argument #3 is the radius #4 is 1 for fill
hold off
pause(0.01)
end
CIRCLE CODE:
function cirkel(x,y,r,f,c)
angle = linspace(0, 2*pi, 360);
xp = x + r*cos(angle);
yp = y + r*sin(angle);
plot(x,y)
if f == 1 && nargin == 5
fill(xp,yp,c)
end
When you call axis equal it makes one unit of the x axis be the same size as one unit of the y axis. You are seeing what you are because your y values span a much larger range than the x values.
One way to deal with this would be to query the aspect ratio and x/y limits of the current axes as shown in the second part of this answer. However, an easier approach is rather than using fill to plot your circle, you could instead use scatter with a circular marker which will be circular regardless of the aspect ratio of your axes.
t = linspace(0,3);
x = 30*cos(pi/4)/2*(1-exp(-0.5*t));
y = (30*sin(pi/4)/2 + 9.81/0.5^2)*(1-exp(0.5*t)) - 9.81*t/0.5;
% Plot the entire curve
hplot = plot(x, y);
hold on;
% Create a scatter plot where the area of the marker is 50. Store the handle to the plot
% in the variable hscatter so we can update the position inside of the loop
hscatter = scatter(x(1), y(1), 50, 'r', 'MarkerFaceColor', 'r');
for k = 1:length(t)
% Update the location of the scatter plot
set(hscatter, 'XData', x(k), ... % Set the X Position of the circle to x(k)
'YData', y(k)) % Set the Y Position of the circle to y(k)
% Refresh the plot
drawnow
end
As a side note, it is best to update existing plot objects rather than creating new ones.
If you want the small dot to appear circular, and you want to have a reasonable domain (x-axis extent), try this:
function cirkel(x,y,r,f,c)
angle = linspace(0, 2*pi, 360);
xp = x + 0.04*r*cos(angle); %% adding scale factor of 0.04 to make it appear circular
yp = y + r*sin(angle);
plot(x,y)
if f == 1 && nargin == 5
fill(xp,yp,c)
end
Note the addition of the scale factor in the computation of xp. If you want to automate this, you can add another parameter to cirkel(), let's call it s, that contains the scale factor. You can calculate the scale factor in your script by computing the ratio of the range to the domain (y extent divided by x extent).

Multiple axes for a single surf plot

I have a surf plot, in which I would like to have two y-axes. I cannot seem to find any other discussion quite like this.
The closest I got so far is:
surf(peaks);
view(0,0)
ax(1) = gca;
axPos = ax(1).Position;
ax(2) = axes('Position',axPos, 'Color', 'none','XTick',[],'ZTick',[],'YAxisLocation','right');
linkprop(ax, 'CameraPosition');
rotate3d on
% Desired plot
surf(peaks);
% Save axis
ax(1) = gca;
% Use the position of the first axis to define the new axis
pos = ax(1).Position;
pos2 = pos - [0.08 0 0 0];
ax(2) = axes('Position',pos2,'Color', 'none');
% Plot random line in 3D, just make sure your desired axis is correct
plot3(ones(length(peaks),1), 10:10:length(peaks)*10,...
ones(length(peaks),1), 'Color','none')
% Make plot, and non-desired axes, invisible
set(gca,'zcolor','none','xcolor','none','Color','none')
% Link axes
linkprop(ax, 'View');

Calculate gradients of a 3d structure in Matlab

I try to use the Matlab function gradient to calculate the gradient of a volume. I use quiver to display the gradients of slices.
I use a cube-like volume, which is symmetric with respect to x, y, and z axis. To my surprise, the result is not the same for all slices. Actually only the result in the xy-plane (Z-slice, last image) is the expected result.
I know that there are issues when calculating the gradient at the border of an image. But for me the result at the border is not important and so I don't care if the result next to the border is correct. For me it would be important that all three images look like the last one.
Can somebody tell me what is wrong with my code? Thanks!
f=zeros(20,20,20);
space = 5;
f(:,:,space) = 1; f(:,:,end-space) = 1;
f(:,space,:) = 1; f(:,end-space,:) = 1;
f(space,:,:) = 1; f(end-space,:,:) = 1;
space = 4;
f(:,:,space) = 1; f(:,:,end-space) = 1;
f(:,space,:) = 1; f(:,end-space,:) = 1;
f(space,:,:) = 1; f(end-space,:,:) = 1;
size_iso = size(f);
x_slice = round(size_iso(1)/2);
y_slice = round(size_iso(2)/2);
z_slice = round(size_iso(3)/2);
% display the gradient of the edge map
[fx,fy,fz] = gradient(f,0.1);
figure;
image(squeeze(f(x_slice,:,:))*50); colormap(gray(64)); hold on;
quiver(squeeze(fy(x_slice,:,:)),squeeze(fz(x_slice,:,:)));
axis equal;
title(['edge map gradient of X-slice ', num2str(x_slice)]);
figure;
image(squeeze(f(:,y_slice,:))*50); colormap(gray(64)); hold on;
quiver(squeeze(fx(:,y_slice,:)),squeeze(fz(:,y_slice,:)));
axis equal;
title(['edge map gradient of Y-slice ', num2str(y_slice)]);
figure;
image(squeeze(f(:,:,z_slice))*50); colormap(gray(64)); hold on;
quiver(squeeze(fx(:,:,z_slice)),squeeze(fy(:,:,z_slice)));
axis equal;
title(['edge map gradient of Z-slice ', num2str(z_slice)]);
Things are bit more complicated with 3D matrices and coordinates.
For example
img = rand(10,30);
imagesc(img);
axis equal;
will display an image 30 pixels wide and 10 pixels high.
In MatLab when you display an image its first dimension (rows) is actually Y-axis on the plot. Second dimension (columns) is X-axis on the plot.
See, for example, http://www.mathworks.com/help/matlab/math/multidimensional-arrays.html
To illustrate mistake in your code consider simplified example:
% we need a 3D matrix with
% 10 points along the X-axis
% 20 points along the Y-axis
% 30 points along the Z-axis
f = rand(20,10,30); % note the order of numbers
size_iso = size(f), % gives [20 10 30]
x_slice = round(size_iso(2)/2) % gives 5
y_slice = round(size_iso(1)/2) % gives 10
z_slice = round(size_iso(3)/2) % gives 15
figure;
image(squeeze(f(:,x_slice,:))*50); colormap(gray(64)); hold on;
axis equal;
title(['X-slice ', num2str(x_slice)]);
% this code produces image 30 pixels wide and 20 pixels high
% Thus 1st dimension (vertical axis) is actually the Y-axis
% Thus 2nd dimension (horizontal axis) is actually the Z-axis
figure;
image(squeeze(f(y_slice,:,:))*50); colormap(gray(64)); hold on;
axis equal;
title(['Y-slice ', num2str(y_slice)]);
% this code produces image 30 pixels wide and 10 pixels high
% Thus 1st dimension (vertical axis) is actually the X-axis
% Thus 2nd dimension (horizontal axis) is actually the Z-axis
figure;
image(squeeze(f(:,:,z_slice))*50); colormap(gray(64)); hold on;
axis equal;
title(['Z-slice ', num2str(z_slice)]);
% this code produces 10 pixels wide and 20 pixels high
% Thus 1st dimension (vertical axis) is actually the Y-axis
% Thus 2nd dimension (horizontal axis) is actually the X-axis
For your code to work properly you should pay attention not only to the order of dimensions in the slice image but also to the way they are shifted by squeeze function.
Therefore you should provide proper combination of coordinates to the subsequent quiver function call.
I modified your code to fill slab perpendicular to given axis with unique value so you should be able to distinguish them easier. Also I'm using different dimensions along each axis for the same purpose.
xvalue=0.33;
yvalue=0.66;
zvalue=1.00;
% we need a 3D matrix with
% 10 points along the X-axis
% 20 points along the Y-axis
% 30 points along the Z-axis
f = zeros(20,10,30); % note the order of numbers
space = 3;
f(:,space,:) = xvalue; f(:,end-space,:) = xvalue;
f(space,:,:) = yvalue; f(end-space,:,:) = yvalue;
f(:,:,space) = zvalue; f(:,:,end-space) = zvalue;
size_iso = size(f);
x_slice = round(size_iso(2)/2); % note dimension number here for x_slice
y_slice = round(size_iso(1)/2); % note dimension number here for y_slice
z_slice = round(size_iso(3)/2);
% display the gradient of the edge map
[fx,fy,fz] = gradient(f,0.1);
figure;
image(squeeze(f(:,x_slice,:))*50); colormap(gray(64)); hold on;
quiver(squeeze(fz(:,x_slice,:)),squeeze(fy(:,x_slice,:)));
axis equal;
title(['edge map gradient of X-slice ', num2str(x_slice)]);
xlabel('Z')
ylabel('Y')
figure;
image(squeeze(f(y_slice,:,:))*50); colormap(gray(64)); hold on;
quiver(squeeze(fz(y_slice,:,:)),squeeze(fx(y_slice,:,:)));
axis equal;
title(['edge map gradient of Y-slice ', num2str(y_slice)]);
xlabel('Z')
ylabel('X')
figure;
image(squeeze(f(:,:,z_slice))*50); colormap(gray(64)); hold on;
quiver(squeeze(fx(:,:,z_slice)),squeeze(fy(:,:,z_slice)));
axis equal;
title(['edge map gradient of Z-slice ', num2str(z_slice)]);
xlabel('X')
ylabel('Y')
Yes, this is tricky and hard to understand at first but you'll get used to it with practice.

How to create mesh on cylindrical surface after generating random points on cylindrical surface

Now I can generate random points on cylindrical surface.
But I cannot create correctly the mesh on cylindrical surface by using generated points.
When I use this code, the triangle mesh created by delaunay triangulation becomes vertically long.
So I want to solve this problem.
I show my code here.
I don't want to change the parameters except for number of points
clear all
close all
clc
n =1000; % Number of points
% Radius
c = 3.0*10^8; % Speed of lgiht
f = 5.2*10^9; % Frequency
lambda = c/f; % Wavelength
r = 3*lambda; % Radius of circular cylinder
theta = rand(1,n)*(2*pi);
% Equation
x = r.*cos(theta);
y = r.*sin(theta);
z = 2*rand(n,1)-1;
% Plot
figure(1)
scatter3(x(:), y(:), z(:),'.')
% axis equal
xlabel('x-length','Fontname','Times New Roman','fontsize',25)
ylabel('y-length','Fontname','Times New Roman','fontsize',25)
zlabel('z-length','Fontname','Times New Roman','fontsize',25)
title('Randomly distributed point cloud on surface of cylinder','Fontname','Times New Roman','fontsize',25)
% Plot range
xlim([-1 1]) % Plot range of x-axis
ylim([-1 1]) % Plot range of y-axis
zlim([-1 1]) % Plot range of z-axis
set(gca,'Fontname','Times New Roman','fontsize',20)
% Create mesh
figure(2)
dt = delaunayTriangulation(x(:),y(:),z(:));
[tri, Xb] = freeBoundary(dt);
tr = TriRep(tri, Xb);
P = incenters(tr);
fn = faceNormals(tr);
trisurf(tri,Xb(:,1),Xb(:,2),Xb(:,3), ...
'FaceColor', 'g', 'faceAlpha', 0.8);
axis equal;
hold on;
quiver3(P(:,1),P(:,2),P(:,3), ...
fn(:,1),fn(:,2),fn(:,3),0.5, 'color','r');
hold off;
xlabel('x-length','Fontname','Times New Roman','fontsize',25)
ylabel('y-length','Fontname','Times New Roman','fontsize',25)
zlabel('z-length','Fontname','Times New Roman','fontsize',25)
title('Randamly distributed point cloud on surface of cylinder','Fontname','Times New Roman','fontsize',25)
% Plot range
xlim([-1 1]) % Plot range of x-axis
ylim([-1 1]) % Plot range of y-axis
zlim([-1 1]) % Plot range of z-axis
set(gca,'Fontname','Times New Roman','fontsize',20)
Please teach me the cause that the mesh becomes vertically long.