Matlab plot syntax is easy to use but apparently easy to forget.

Here I’m plotting the line y = x2 from x = -20 to +20.


% generate x, y vectors
x = -20:0.01:20;   % x goes from -20 to 20 in steps of 0.01
y = x.^2;            % generate y
plot(x,y);

y = x^2

Hmm the plot would be easier to see if it had grid lines drawn in.


% generate x, y vectors
x = -20:0.01:20;   % x goes from -20 to 20 in steps of 0.01
y = x.^2;            % generate y
plot(x,y);
grid on;

Hmm, I want to zoom the plot in so it shows from -2 to +2 of the x-axis and from -1 to +3 of the y-axis.


% generate x, y vectors
x = -20:0.01:20;   % x goes from -20 to 20 in steps of 0.01
y = x.^2;            % generate y
plot(x,y);
grid on;
axis( [-2, 2, -1, 3] );  % NOTICE this goes AFTER the plot() command, [ xmin, xmax, ymin, ymax ]
% you must have the [], the axis function takes ONE argument with vector type, not 4 different arguments.


Finer control

We can get much finer control over our matlab plots by ACQUIRING THE HANDLE to the axes.

The axes exist as an object in memory somewhere inside the MATLAB “machine”. The ‘handle’ to the axes is YOUR POINTER that you can use to make changes to that axes object, even though the MATLAB program isn’t fully under your control. You have control over PARTS of MATLAB THROUGH these handles you can get.

This is easy.

So howdya get the handle?


% generate x, y vectors
x = -20:0.01:20;   % x goes from -20 to 20 in steps of 0.01
y = x.^2;            % generate y
plot(x,y);

HANDLE = gca;  % "get current axis handle" . . gives you "handle" to the axes that belong to the plot you JUST made.
% Remember, a HANDLE to the axes are just a programmatic "means to control" the axes.

% now try this
get( HANDLE );

%% wow!  you'll see a huge listing here like
%	ActivePositionProperty = outerposition
%	ALim = [0 1]
%	ALimMode = auto
%	AmbientLightColor = [1 1 1]
%	Box = on

% You can customize any of these by choosing something, then SETTING the property using the SET function.

% e.g. let's change the background color to dark blue, and the axes color to
set( HANDLE, 'Color', [0,0.1,0.2] ); %background color to dark blue


How do you change the color of the matlab plot itself?


% generate x, y vectors
x = -20:0.01:20;   % x goes from -20 to 20 in steps of 0.01
y = x.^2;            % generate y
plothandle = plot(x,y);

% now try this
get( plothandle ) ;
%lists all properties you can change of the PLOT itself

set( plothandle, 'Color', [ 1, 0.5, 0 ] );  % plot color to orange
set ( plothandle, 'LineWidth', 1.5 );   % make matlab plot line wider


altered colored matlab plot . . the altered beast if you will

All the stuff in this section uses code like:

set( HANDLE, 'PropertyName', PropertyValue ) ;

ref

Post a Comment