How to change the axes position in matlab

74 visualizaciones (últimos 30 días)
Chuzymatics Chuzymatics
Chuzymatics Chuzymatics el 10 de Ag. de 2014
Comentada: Paul el 20 de En. de 2025
Hi Everybody! I want to be able to relocate my axes/the origin (0, 0) of my plot to the middle of the graphics window. I don't know how to manipulate the set command to do this. There must be a way. Regards
% Code explores advanced graphics properties
clf
x= 0:pi/10:pi;
angle = x.*180/pi;
y = -sind(angle);
h =plot(angle, y)
set(h, 'color', 'red')
set(h, 'marker','s')
set(h, 'LineWidth', 2)
h_axis =gca; % Manipulate theaxis next
set(h_axis, 'LineWidth', 2)
  3 comentarios
Chuzymatics Chuzymatics
Chuzymatics Chuzymatics el 11 de Ag. de 2014
Yeah, I want to set the position of the axes object
Chuzymatics Chuzymatics
Chuzymatics Chuzymatics el 11 de Ag. de 2014
Please take a look at the attached file to understand what I am talking about. Pay attention to the position of the x and y axes. Thanks

Iniciar sesión para comentar.

Respuesta aceptada

Rob Comer
Rob Comer el 8 de Ag. de 2024
This question is 10 years old, but it's worth answering given that there have been 78 views in the past 30 days and my answer uses some axes property settings that should become more widely known. Here's a workable way to approach it.
The axis location properties of the Axes object, XAxisLocation and YAxisLocation, can be set to "origin", providing the essentials of what is needed to reproduce the figure that Chuzymatics provided here: axes_translated.jpeg. That figure shows a plot of the sin() function on the interval [0 2*pi], with the x-axis intersecting the y-axis at 0 and the y-axis intersecting the x-axis at pi.
See the script provided below.
Notes
  • I'm not sure if these location properties could be set to "origin" in 2014 when the question was originally posted, but I've used them recently and found them to be very useful.
  • In the figure from Chuzymatics (axes_translated.jpeg) the y-axis intersects the x-axis at pi, rather than at 0. There's no way that I know of to set YAxisLocation to a custom numeric value, but my script shows an easy workaround based on shifting x by pi before plotting the sine curve and applying a compensating shift to the TickLabels on the x-axis.
  • My script sets a few additional properties on the axes rulers (ax.XAxis and ax.YAxis) in order to match the tick directions, minor tick locations, and number of decimal places from the tick labels in axes_translated.jpeg.
%% Evaluate sin() between 0 and 2*pi
u = linspace(0, 2*pi, 91);
y = sin(u);
%% Prepare to place the y-axis such that it intersects the x-axis at pi
% Shift input values (u) and horizontal tick values by the same amount
xAxisLocation = pi;
x = u - xAxisLocation;
uTickValues = [0, pi, 2*pi];
xTickValues = uTickValues - xAxisLocation;
%% Plot sin(u) and set both axis locations to the origin
figure
plot(x,y)
ax = gca;
set(ax, XAxisLocation="origin", YAxisLocation = "origin")
%% Turn off box and give axes and parent figure the same color
box off
set(ax.Parent,"Color",ax.Color)
%% Customize ticks and tick labels on x-axis
xTickLabels = split(sprintf("%.3f ",uTickValues));
xTickLabels(end) = [];
set(ax.XAxis, TickValues=xTickValues, TickLabels=xTickLabels, ...
TickDirection="out", MinorTick="on")
%% Customize ticks and tick labels on y-axis
yLimits = [-1.2, 1.2];
delta = 0.1;
ylim(yLimits + [-1 1]*delta)
yTickValues = linspace(yLimits(1), yLimits(2), 7);
yMinorTickValues = linspace(yLimits(1), yLimits(2), 31);
set(ax.YAxis, TickValues=yTickValues, TickLabelFormat="%.3f", ...
TickDirection="out", MinorTick="on", MinorTickValues=yMinorTickValues)
  4 comentarios
Jon
Jon el 20 de En. de 2025
I was experimenting to see if I could use XAxisLocation without creating a variable ax, and XAxisLocation was not working until I tried gcf().CurrentAxes. I have now experimented more and have found the following repeatable example.
fplot(@sin, [-10 10]);
ax = gca;
ax.XAxisLocation = "origin";
% That worked. Now try an incorrect use of gca.
fplot(@sin, [-10 10]);
gca.XAxisLocation = "origin";
% The x-axis is not moved. Now try with correct use of gca.
ax = gca;
ax.XAxisLocation = "origin";
fplot(@sin, [-10 10]);
ax = gca;
ax.XAxisLocation = "origin";
% This is not working. So try gcf().
ax = gcf().CurrentAxes;
ax.XAxisLocation = "origin";
% That works!
When gca has stopped working, the only way I know to fix it is to exit MATLAB and then reopen MATLAB Online. By the way, I got the idea of using gcf from the Tips section of the gca help page.
Paul
Paul el 20 de En. de 2025
"They ought to be essentially the same in almost all respects"
suggests that ax = gcf().CurrentAxes and ax = gca;
might be subtly different. Any idea what those differences might be?

Iniciar sesión para comentar.

Más respuestas (3)

dpb
dpb el 10 de Ag. de 2014
Not a settable choice in handle graphics -- x-axis can be "top|bottom" and y is either "left|right" -- "center" isn't a choice. Seems strange a a weakness, granted.
Try the File Exchange to see if somebody has submitted a package with the ability; otherwise one has to make it by drawing the axis manually at the location desired or fake it by using two axes each of half the size to split in the middle, say.

Geoff Hayes
Geoff Hayes el 10 de Ag. de 2014
Chuzymatics - if you are just trying to move the origin (0,0) to the centre of the figure, then you could try the following which just resets the axes limits so that (0,0) is in the centre. From your above code, you have the handle to the current axes
% handle to the current axes
h_axis =gca;
% determine the max absolute value along the x-axis
maxX = max(abs(get(h_axis,'XLim')));
% determine the max absolute value along the y-axis
maxY = max(abs(get(h_axis,'YLim')));
% now reset the limits for the axes so that (0,0) is in the centre
axis(h_axis,[-maxX maxX -maxY maxY]);
Or, instead of axis , you can use xlim and ylim.
Try the above and see what happens!
  3 comentarios
dpb
dpb el 11 de Ag. de 2014
See above...will have to draw the axes in the center or, hopefully, there's a File Exchange submission that does so...
Geoff Hayes
Geoff Hayes el 11 de Ag. de 2014
Editada: Geoff Hayes el 11 de Ag. de 2014
A similar request was made at move the axes. The code that is attached to the answer is a file called drawaxis.m...though it didn't quite do what I thought it would. I modified it in two places by replacing
if (myX_Crossing< props.XLim(1)) | (myX_Crossing> props.XLim(2))
error('Specified X crossing outside axis limits')
return
end
with
if (myX_Crossing< props.YLim(1)) || (myX_Crossing> props.YLim(2))
error('Specified X crossing outside y-axis limits')
end
and replacing
if (myY_Crossing< props.YLim(1)) | (myY_Crossing> props.YLim(2))
error('Specified Y crossing outside axis limits')
return
end
with
if (myY_Crossing< props.XLim(1)) || (myY_Crossing> props.XLim(2))
error('Specified Y crossing outside x-axis limits')
end
To use, just do as follows
% plot the function
x=0:0.0001:2*pi;
y=sin(x);
plot(x,y);
% move the axes so that the y-axis is located at pi along the
% x-axis, and the x-axis is located at 0 along the y-axis
drawaxis(gca, 'y', pi)
drawaxis(gca, 'x', 0)
Note that moving the graphic after that may cause the axes to become disrupted.

Iniciar sesión para comentar.


dpb
dpb el 11 de Ag. de 2014
Editada: dpb el 11 de Ag. de 2014
A start...still, check File Exchange; may already be done for you...
>> x=linspace(0,2*pi,100); y=sin(x);
>> plot(x,y)
>> set(gca,'visible','off')
>> line([0 2*pi],[0 0],'color','k')
>> line([pi pi],[-1.2 1.2],'color','k')
>> xlim([0 2*pi]), ylim([-1.2 1.2])
>> text([0:pi:2*pi],-0.1*ones(1,3),num2str([0:pi:2*pi].','%0.3f'), ...
'horizontal','center','vertical','top','fontsize',8)
Add text for the vertical similarly as well as the ticks w/ a series of line segments.
But, as expected, there's a routine from Matt Figg at FileExchange --
that has rave revues...

Categorías

Más información sobre Creating, Deleting, and Querying Graphics Objects en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by