How to change the axes position in matlab
    86 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
    Chuzymatics Chuzymatics
 le 10 Août 2014
  
    
    
    
    
    Commenté : Paul
      
      
 le 20 Jan 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 commentaires
Réponse acceptée
  Rob Comer
 le 8 Août 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 commentaires
  Jon
 le 20 Jan 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
      
      
 le 20 Jan 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?
Plus de réponses (3)
  dpb
      
      
 le 10 Août 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.
0 commentaires
  Geoff Hayes
      
      
 le 10 Août 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]);
Try the above and see what happens!
3 commentaires
  dpb
      
      
 le 11 Août 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
      
      
 le 11 Août 2014
				
      Modifié(e) : Geoff Hayes
      
      
 le 11 Août 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.
  dpb
      
      
 le 11 Août 2014
        
      Modifié(e) : dpb
      
      
 le 11 Août 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...
0 commentaires
Voir également
Catégories
				En savoir plus sur Creating, Deleting, and Querying Graphics Objects dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
