Aqua Phoenix
     >>  Lectures >>  Matlab 8  
 

Navigator
   
 
       
   

8.5 Plotting

In Matlab, plotting refers to producing 2-dimensional graphs, while meshing refers to 3-dimensional graphs. Since a 2-dimensional graph is merely a collection of points, the command plot takes as input a vector and simply plots the numbers.

Given vector Y, the command plot(Y) plots the point in the vector. Without passing a separate vector with x-values, each point in vector Y is mapped linearly to a point on the x-axis. For example, if Y = [10, 7, -9, 0, 1] , then the corresponding X values are [1, 2, 3, 4, 5] , respectively. If this scale is not desirable, an X vector with a different scale can be passed as an argument to the function plot.

Figure 8.10
Click image to enlarge, or click here to open
Given vectors X and Y, where X contains regularly or irregularly spaced sample points on the X axis, and Y contains the corresponding values in the Y direction, the command plot(X,Y) plots a graph of Y with the scale of X.

Figure 8.11
Click image to enlarge, or click here to open
For example, consider the following data points:

y=[16,50,70,104,106,104,95,80,67,59,87,124,153,157,144,127,...
109,90,71,100,134,163,178,179,174,161,141,117,93,76,89,105,...
123,140,153,156,144,128,106,86,65,48,30,17,24,29,25,21,16,7];
Plotted in regular (default) scale assigns each data point to a proportionally increasing (+ 1) x value:

plot(y);
Figure 8.12
Click image to enlarge, or click here to open
x=[10,5,3,2,9,14,17,20,25,27,28,29,30,38,45,49,52,54,58,...
59,60,62,66,72,78,81,82,84,87,90,97,102,106,109,112,119,...
125,128,126,122,118,117,121,134,154,174,190,194,194,185];
Given a different data range corresponding to the same y-data the graph exhibits distinct differences.

plot(x,y);
Figure 8.13
Click image to enlarge, or click here to open
String modifiers can be used to change color, data point, and line styles. A summary is given in table 8.2.

Colors Point style Line style
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
Table 8.2
At most one modifier can be taken from each column and concatenated to result in a unique line/point/color style. For example:

plot(x,y,'r');
Figure 8.14
Click image to enlarge, or click here to open
plot(x,y,'g:');
Figure 8.15
Click image to enlarge, or click here to open
plot(x,y,'md:');
Figure 8.16
Click image to enlarge, or click here to open
A figure's background color can be changed using the command whitebg . For example:

whitebg('k')
Figure 8.17
Click image to enlarge, or click here to open
whitebg('y')
Figure 8.18
Click image to enlarge, or click here to open

8.5.1 Bar Charts

2D bar graphs plot data points in terms of their area. Given some random data:

xBar=[1:10];
yBar=rand(1,10) * 100;
a bar chart is produced using:

bar(xBar,yBar);
Figure 8.19
Click image to enlarge, or click here to open
2D bar charts can also be created for matrices, in which case each row in the matrix is considered as one group of bars. The resulting graph distinguishes matrix columns with different colors.

yBar=rand(7,3);
bar(yBar);
Figure 8.20
Click image to enlarge, or click here to open
3D bar graphs are easily obtained from matrices as well, using the bar3 command:

bar3(yBar)
Figure 8.21
Click image to enlarge, or click here to open

8.5.2 Labels

Common properties of all figures, whether 2D or 3D, plots, bar graphs, meshed, etc. are axes labels, titles. Every figure should be properly labeled for clarity.

Axes labels can be assigned using commands xlabel , ylabel , or zlabel , selectively or in combination:

plot(x, y, 'r*-.'), xlabel('South'), ylabel('West')
Figure 8.22
Click image to enlarge, or click here to open
A title is added by using the command title :

plot(x, y, 'r*-.'), xlabel('South'), ylabel('West'), title('Mysterious Constellation of a Waiving Hand');
Figure 8.23
Click image to enlarge, or click here to open
By default, the data range of x is used for labeling individual tick marks on the x-axis. Alternatively, named values can be used as replacements.

x=1:8;
y=rand(1,8) * 100;
plot(x,y);
set(gca, 'XTickLabel', {'Earth', 'Mercure', 'Saturn', 'Venus', 'Pluto', 'Neptune', 'Mars', 'Jupiter'})
The command set in this case changes property XTickLabel for figue handle gca (default figure) to a vector of strings.

Figure 8.24
Click image to enlarge, or click here to open
Using the data imported from regions.csv, we plot the data matrix, and assign labels from the previously created vector dates:

plot(data(:,1));
set(gca, 'XTickLabel', dates);
This plot does not, however, exhibit the correct labels. Because of the large number of labels, Matlab decides to space them apart, seemingly irrationally.

Figure 8.25
Click image to enlarge, or click here to open
To display all tick marks on the x-axis, the following series of commands are necessary:

plot(data(:,1));
set(gca, 'XTick', 1:length(dates));
However, this x-axis is not readable, which is my Matlab distributed the tick marks in the first place.

Figure 8.26
Click image to enlarge, or click here to open
The following expressions help in spacing out the tick marks, while maintaining the correct index into the label vector:

plot(data(:,1));
set(gca, 'XTick', 20:50:length(dates));
Essentially, starting at label index 21, every 50th label index is used for tick marks.

Figure 8.27
Click image to enlarge, or click here to open
To show the actual dates for these tick marks, we replace them using the XTickLabel feature:

plot(data(:,1));
set(gca, 'XTick', 20:50:length(dates));
set(gca, 'XTickLabel', dates(20:50:length(dates)));
Figure 8.28
Click image to enlarge, or click here to open
In cases where the x-axis is labeled with long strings per tick mark, it is desirable to use slanted labels. While Matlab's plot function does not allow for rotation of labels, there exist functions that replace the mechanism by which labels are placed on the x-axis. One such function can be downloaded here:

  xticklabel_rotate.m  
Given an existing plot with numerical labels on the x-axis, the function xticklabel_rotate rotates all labels by 90o.

a=rand(1,30);
plot(a);
xticklabel_rotate;
Figure 8.29
Click image to enlarge, or click here to open
To rotate the labels for a different amount, the degree can be passed as a second parameter. The first parameter in this example remains empty (empty set []). This signifies that the x-ticks or labels should not be changed, but merely rotated.

plot(a);
xticklabel_rotate([], 45);
Note: Once the function xticklabel_rotate has been applied once to a given graph, it cannot be applied again. The plot command needs to be re-executed, and xticklabel_rotate needs to be called again.

Figure 8.30
Click image to enlarge, or click here to open
If it is desirable to use different x-tick spacings, as discussed above (see Figures 8.26, 8.27, and 8.28), the function xticklabel_rotate can be used instead of the function set(gca, ...). xticklabel_rotate can set the vector of x-ticks as well as the labels, whether numerical or text.

Using xticklabel_rotate on the dataset of gasoline prices, it makes sense to space the x-tick marks farther apart, because there are too many to fit on the x-axis. We pass an indexed vector as a first parameter to space out the x-tick marks:

plot(data(:,1));
xticklabel_rotate(20:15:size(data,1), 45);
This displays and rotates every 15th tick label on the x-axis.

Figure 8.31
Click image to enlarge, or click here to open
Finally, to display dates (textual data) as opposed to numerical labels, we pass the cell vector as a third parameter. The cell vector is properly indexed to match the x-tick vector (first parameter):

plot(data(:,1));
xticklabel_rotate(20:15:size(data,1), 45, dates(20:15:size(dates)));
Figure 8.32
Click image to enlarge, or click here to open

8.5.3 Overlaying plots

Several plots can be placed in the same figure by overlaying them.

The simplest approach is to plot a matrix of values, in which each column is interpreted as one vector.

y=rand(10, 3);
plot(y);
Figure 8.33
Click image to enlarge, or click here to open
For the example of gasoline prices in regions.csv:

plot(data);
Figure 8.34
Click image to enlarge, or click here to open
Alternatively, vectors can also be placed in the same graph individually by using the hold on and hold off functions:

hold on;
plot(data(:,2),'r');
plot(data(:,4),'g');
plot(data(:,6),'b');
plot(data(:,8),'y');
hold off;
Figure 8.35
Click image to enlarge, or click here to open
For multi-line graphs, legends can be added for descriptive purposes. The function legend takes as many string arguments as there are plots, and assigns each string to a plot, in the order in which they were placed in the graph:

legend('the red graph', 'the green graph', 'the blue graph', 'the yellow graph');
Figure 8.36
Click image to enlarge, or click here to open
Using the actual labels from textdata:

legend(regions(1,2:2:8));
Figure 8.37
Click image to enlarge, or click here to open

8.5.4 Meshing (3d graphs)

3D graphs are generated using the function mesh or surf . Given a 2D matrix of values, each value is used as a z-value (elevation), and placed in a 3D view.

Given a function of sine and cosine:

z=[];
for i=1:100
    for j=1:100
        z(i,j) = sin(i/10) + cos(j/10);
    end
end
mesh(z);
creates a mesh (with holes)

Figure 8.38
Click image to enlarge, or click here to open
surf(z);
creates a mesh with filled patches (a surface).

Figure 8.39
Click image to enlarge, or click here to open
For the data set of gasoline prices per region, a viable mesh would be:

mesh(data);
Figure 8.40
Click image to enlarge, or click here to open
And labels, and titles can be added as appropriate:

mesh(data);
title('Gasoline prices in U.S. regions');

xlabel('Region');
ylabel('Date');
zlabel('Price in cents');

set(gca, 'XTick', 1:length(regions));
set(gca, 'XTickLabel', regions);

set(gca, 'YTick', 20:50:length(dates));
set(gca, 'YTickLabel', dates(20:50:length(dates)));
Figure 8.41
Click image to enlarge, or click here to open

8.5.5 Multiple plots

Using the subplot function, it is possible to generate separate plots in a grid of figures.

SUBPLOT(M, N, P) creates a grid of figures for M rows, N columns, and fills the Pth cell with the next figure.

Example:

subplot(3, 2, 1), plot(rand(1, 10));
subplot(3, 2, 2), bar(rand(1, 10));
subplot(3, 2, 3), surf(rand(20));
subplot(3, 2, 4), hist(rand(50));
subplot(3, 2, 5), plot(sin([0:0.1:10]));
subplot(3, 2, 6), plot(rand(1,100),'gd:');
Figure 8.42
Click image to enlarge, or click here to open
Each figure can be assigned its own labels and titles:

Figure 8.43
Click image to enlarge, or click here to open
subplot(3, 2, 1), plot(rand(1, 10)), xlabel('x-axis 1'), ylabel('y-axis 1'), title('random line');
subplot(3, 2, 2), bar(rand(1, 10)), xlabel('x-axis 2'), ylabel('y-axis 2'), title('random bars');
subplot(3, 2, 3), surf(rand(20)), xlabel('x-axis 3'), ylabel('y-axis 3'), zlabel('z-axis 3'), title('random surface');
subplot(3, 2, 4), hist(rand(50)), xlabel('x-axis 4'), ylabel('y-axis 4'), title('random histogram');
subplot(3, 2, 5), plot(sin([0:0.1:10])), xlabel('x-axis 5'), ylabel('y-axis 5'), title('sine wave');
subplot(3, 2, 6), plot(rand(1,100),'gd:'), xlabel('x-axis 6'), ylabel('y-axis 6'), title('Matrix, the Movie');