Whats wrong with the following commands?

% The plotted x-axis goes from 0 to 1, instead of 20. Why?
ax = gca;
ax.xlim = [0 20];
drawnow

3 Comments

I have a small example for you
time=[0:2:24];
data=[5;6;12;18;15;16;18;15;10;9;8;7;7];
figure(1);
plot(time,data,'r','LineWidth',2);
ax=gca;
ax.XLim = [0 20];
grid on;
title('test','fontsize',12,'fontweight','bold');
xlabel('x-axis','fontsize',12,'fontweight','bold');
ylabel('y-axis','fontsize',12,'fontweight','bold');
Regards, John

This code worked as expected for me. See attached.

yes, but you can see, that I want to set axes before drawing the plot or plotting anything! This is not possible? The problem is that axes are created with the plot command and not existed before? How to set axes before and plot shapes after?

Sign in to comment.

 Accepted Answer

By default, calling PLOT resets most of the axes properties. See the description of "hold off" in the documentation for HOLD as well as the description of the axes property NextPlot for more information. To do what you want, use HOLD or the NextPlot axes property.

More Answers (1)

This code worked for me:

figure
plot(rand(7,5))
ax = gca;
ax.XLim = [0 20];
drawnow

(I changed the capitalization of ax.XLim.)

6 Comments

yes, but you can see, that I want to set axes before drawing the plot or plotting anything! This is not possible? The problem is that axes are created with the plot command and not existed before? How to set axes before and plot shapes after?
disp('Create the figure window with default axes, and "hold" so that later axes add on, rather than replace.')
figure
hold on
pause(2)
disp('Resize the axes')
ax = gca;
ax.XLim = [0 20];
pause(2)
disp('Add a plot')
plot(rand(7))
pause(2)
disp('Bye bye')
This is NOT working for me!
figure;
hold on;
ax = gca;
ax.XLim = [0 20];
plot([],[]);
drawnow;

Strange. Works for me. The output of those commands is attached below. (R2015a on Mac OS X 10.10.5.)

my otput is the same but x-axis goes to 1 instead of 20! I cannot understand why?!
I hope this fixes your Problem. With hold(ax,'on') it is not possible for the plot command to update the axis.
figure
ax = gca;
ax.XLim = [0 20];
hold(ax,'on')
plot([],[])
Regards, John

Sign in to comment.

Categories

Asked:

on 30 Sep 2015

Edited:

on 1 Oct 2015

Community Treasure Hunt

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

Start Hunting!