3

MATLAB® graphics

Abstract

Graphic presentations of observed data, test results, and various calculations are widely used in the sciences and technology in general and in quality-assurance sciences in particular. MATLAB® has a large assortment of commands for these objectives. These commands allow the generation of two- (sometimes called XY or 2D) and three-dimensional (XYZ or 3D) plots.

Two-dimensional graphics make it possible to draw linear, semi- or logarithmic plots, bars or histograms, pies, Pareto charts, scatter plots, and many other visuals. Several curves can be plotted on a plot and several plots can be presented in the separate Figure Window. A generated plot can be formatted to create the desired style of line or marker form, its thickness or color. In addition, a new line, grid, text, caption or legend can be added to the plot.

To present data involving more than two variables, plots having three axes are used. MATLAB® provides a variety of means for visualizing three-dimensional data that allow the construction of spatial lines, mesh- and surface plots, various geometrical figures and images. Generated plots can be formatted using commands or interactively from the Figure Window.

The most important commands for two- and three-dimensional plots will be presented below. The descriptions that follow are based on the assumption that the reader has thoroughly studied the preceding chapter and therefore, in most cases, explanations to commands are written as inline MATLAB® comments - next to the percentages (%) and not in special frames, as in Chapter 2.

Key words

plots

specifiers

properties

formatting

rotationing

Pareto

3.1 Generation of XY plots

The plot command is the basic command used for XY plotting. In its simplest form it can be written as:

plot(y) or plot(x,y)

where x and y are two vectors of equal length, the first used for the horizontal axis and the second, for the vertical axis.

In the first form of the plot command, the y values are plotted versus their indices. After inputting the plot command with the given values of x and y, the curve y(x) is created in the MATLAB® Figure Window with a linear scale by default. For example, to assure the quality of an antibiotic, a pharmaceutical company checks the acidity level (pH) of the bacterial broth. The pH level is tested for a time span of five hours, every half hour; the results are: 8.32, 8.44, 8.46, 8.49, 8.76, 8.79, 8.40, 8.41, 8.60, 8.65, 8.86. To generate a plot using these data with the x-axis as time and the y-axis as pH the following commands should be typed in the Command Window:

>> t = 0:.5:5;

>> pH = [8.32 8.44 8.46 8.49 8.76 8.79 8.40 8.41 8.60 8.65 8.86];

>> plot(t, pH)

After entering these commands, the Figure Window opens, showing the pH-time plot as shown in Figure 3.1.

f03-01-9780857094872
Figure 3.1 The tested pH of the bacterial broth plotted with default settings

If we want to change the line style and/or marker type, the thickness or color, the plot command is used with the addition of optional arguments written just after the x and y identifiers:

plot(x,y, 'Line Specifiers', 'Property Name', 'Property Value')

where the Line Specifiers determine the line type, the marker symbol and the color of the plotted lines (see Table 3.1; the Property Name assigns properties to be specified by the Property Value). Some of the possible properties and required values are shown in Table 3.2.

Table 3.1

Specifiers for the 'Line Specifiers' character string*

Line styleSpecifierLine colorSpecifierMarker typeSpecifier
Solid(default)-Blue (default for single line)bCircleo
Dotted:GreengAsterisk*
Dash-dot-.RedrPoint.
Dashed- -BlackkSquares
(none)no lineYellowyDiamondd
CyancPlus+
MagentamTriangle (inverted)v
WhitewTriangle (upright)^
Five-pointed asteriskp or pentagram
Six-pointed asteriskh or hexagram

t0010

* Incomplete

Table 3.2

Available property names, values, and purposes*

Property name (Spelling)What specifiesProperty value
LineWidth or linewidthThe width of the lineA number in points (1 point = 1/72 inch). The default line width is a half point
MarkerSize or markersizeThe size of the marker (by the symbol)A number in points. The default value is 6. For the '.' marker: 1/3 of the specified size
MarkerEdgeColor or markeredgecolorThe color of the marker or the edge color for filled markersA character based on the color specifiers in Table 3.1
MarkerFaceColor or markerfacecolorThe fill color for markers that have a closed area (e.g., a circle or square)A character based on the color specifiers in Table 3.1

* Incomplete

Property names and property values, as well as line specifiers, are typed in the plot commands as character strings inside inverted commas. The specifiers and property names with their values can be written in any order, and one or more of them can be omitted altogether. In this case, the default properties are used.

Below are examples of the plot command with specifiers and properties:

plot(y,'-m')Generates the magenta solid line with x-equidistant y points.
plot(x,y,'o')Generates the points with x,y- coordinates marked by a circle.
plot(x,y,'y')Generates the yellow solid (default) line that connects the points.
plot(x,y,'-p')Generates the blue (default) dashed line, with points marked with the five-point asterisk.
plot(x,y,'k:h')Generates the black dotted line, with points marked with the six-point asterisk.
plot(t,pH,'-mo','LineWidth',4,'MarkerSize',10,'markeredgecolor','k', 'MarkerFaceColor','y') Plots the magenta 3-point solid line (1 point = 1/72 inches in size), x,y-values marked with 10-point black-edged yellow circles.

t0025

Entering the last command with previously used bacterial broth data, we can obtain the plot shown in Figure 3.2.

f03-02-9780857094872
Figure 3.2 The tested pH level generated by the plot command with specifiers and property settings

In the examples above, the plots are presented by the x,y-points, obtained in measurements. In this case, we say that the data is given as a table. In many cases, the function can be given as a y(x) expression, in which case the vector of y-values should be calculated at the given vector of x-values (see example in Subsection 3.1.2.3. below).

Note:

 Type and enter the close command in the Command Window to close one Figure Window; to close more than one Figure Window use the close all command.

 Each time the plot command is inputted, the previous plot is deleted.

3.1.1 More than one curve on the single 2D plot

At least two options can be used in MATLAB® to create a graph of two or more curves in the same plot: in the first option, by typing the pairs of x,y-vectors into the plot command and in the second, by using the hold on … hold off commands.

The plot command option

The commands for creating two or more curves in a single plot have forms:

plot(x1,y1,x2,y2) or plot(x1,y1,x2,y2,…,xn,yn)

where x1 and y1, x2 and y2, xn and yn are pairs of equal-length vectors containing the x,y-data. These commands create graphs with two or n curves respectively. For example, plot in one plot the test results of the ash percentages of two different series of five coal lots each, unloaded from a ship, and tested. The results are 10.00, 9.20 6.80 8.45, 10.12 and 9.24, 9.18, 7.20, 8.51, 10.20%. To generate the graph, enter the following commands (without comments) in the Command Window:

>> x = [1:5];%creates vector x
>> y1 = [10 9.2 8.8 8.45 10.12];%creates vector y1
>> y2 = [9.24 9.18 8.2 8.51 10.2];%creates vector y2
>> plot(x,y1,x,y2,'--k')%generates two lines: solid and dashed, the latter - in black.

The resulting plot with two curves is shown in Figure 3.3.

f03-03-9780857094872
Figure 3.3 Two curves in the single plot; percentage of coal ash content by lot

To generate more than two curves in the same plot, two new x,y-vectors should be added in the plot command for each additional curve.

The hold command option

Another option for generating plots with more than one curve is to add a new curve to an existing plot; for this, type the hold on command and the new curve will be created with a new plot command. To complete the hold on process, enter the hold off command, which stops the hold process and shows the next graph in the new Figure Window. For example, the new series of coal ash content: 9.02, 8.72, 7.60, 8.89, 10.00, in percentages, measured in five lots, can be added to the existing graph shown in Figure 3.3 by entering the additional commands:

>> y3 = [9.02 8.72 7.60 8.89 10.00]; % create new vector y

>> hold on

>> plot(x,y3,':r') % add dotted red line to the existing plot

>> hold off

The generated plot is shown in Figure 3.4.

f03-04-9780857094872
Figure 3.4 Three series of coal ash content in the single plot, produced with the hold on/off command option

3.1.2 Several plots on the same page

It is often desirable to place multiple plots on the same page, or, in other words, in the same Figure Window. For this, use the subplot command, which can be written in two forms:

subplot(m,n,p) and subplot mnp

The command divides the page into m by n panes where m and n are the rows and columns of the panes and p is the plot number that this command makes current (see panes and plot numbering, Figure 3.5(a)). The p can be a vector with two or more adjacent panes, meaning that the plots can be arranged asymmetrically so that one of the plots can be placed into two or more columns or rows (see Figure 3.5(b)).

f03-05-9780857094872
Figure 3.5 The page arranged in (a) four and (b) three panes

For example:

subplot(2,2,4) or subplot 224Divides the page into 4 panes ordered in 2 rows and 2 columns and makes subplot 4 current.
subplot(2,2,[1,2])Divides the page into 4 panes and spans the first and second panes (the top of the current page); the first plot is current.
subplot(2,3,2) or subplot 232Divides the page into 6 panes ordered in 2 rows and 3 columns and makes subplot 2 current.
subplot(2,1,2) or subplot 212Divides the page into 2 panes arranged in a single column and makes the last subplot current.
subplot(1,2,1) or subplot 121Divides the page into 2 panes arranged in a single row and makes the first subplot current.

As an exercise, generate three plots on one page, placed in the panes as per Figure 3.5(b): an ellipse, with its coordinates given in the parametric form x = 3sin(t) and y = 5cos(t), the pH data plot (as per Figure 3.2) and the coal ash percentage plot (as per Figure 3.4). The MATLAB® command for generating the plots is:

>> subplot(2,2,[1,2])% makes panes 1 and 2 current
>> t = 0:pi/100:2*pi;% creates the t vector
>> plot(5*sin(t),4*cos(t));% plots the ellipse
>> subplot(2,2,3)% makes pane 3 current
>> t_pH = 0:.5:5;% creates the t_pH vector
>> pH = [5.52, 5.73, 5.84, 6.26, 6.32,6.3, 6.04, 6.09, 5.94, 6.03, 6.12];%pH vector
>> plot(t_pH,pH,'-mo',
'LineWidth',2,'MarkerSize',5,
'markeredgecolor','k',…
'MarkerFaceColor','y')% generates the pH plot
>> subplot(2,2,4)% makes pane 4 current
>> x = [1:5];%creates vector x
>> y1 = [10 9.2 8.8 8.45 10.12];%creates vector y1
>> y2 = [9.24 9.18 8.2 8.51 10.2];%creates vector y2
>> y3 = [9.02 8.72 7.60 8.89 10.00];% creates vector y3
>> plot(x,y1,x,y2,'--k',x,y3,':r')% generates the ash plot

The resulting plot is shown in Figure 3.6.

f03-06-9780857094872
Figure 3.6 Three plots in a single page

3.1.3 Formatting 2D plots

Usually, a figure must have a title, grid, axis labels, suitable axes ranges, text, different colors and various types of curve lines. This can be accomplished by either using special commands or interactively, using the Plot Tools editor (see Subsection 3.1.3.2), accessible from the Figure Window.

3.1.3.1 Commands for 2D plot formatting

Plot formatting commands should be entered after the plot command. The most common commands are described below.

The grid command

To introduce a grid on the current plot use the grid or grid on commands. The grid off command removes the grid lines from the latticed plot. For example, typing grid in the Command Window immediately after the commands that produced Figure 3.3, will draw the grid lines in the figure.

The axis command

This command is used for the appearance and scaling of the axis. Some of its possible forms are:

axis([x_min x_max y_min y_max])

axis equal

axis tight

axis off

The first form adjusts the x and y axes to the limits written in the brackets; the second sets the same scale for the x and y axes (the ratio x/y, width-to-height, is called the aspect ratio); the third sets the axis limits to the range of the data to be performed on the plot; and the last removes the axis and background from the plot.

As an example, enter the sequence commands that calculate sine and cosine, plot them, and set axis limits with the axis tight command:

>> x = linspace(0,2*pi);% 2*pi is maximal values of x
>> y1 = sin(x);y2 = cos(x);% 1 is maximal value of y1 and y2
>> plot(x,y1,x,y2,'--k')% creates plot with x_max not equal to 2pi
>> axis tight% sets x and y limits to 2pi and 1 respectively.

The results are shown in Figures 3.7(a) and (b).

f03-07-9780857094872
Figure 3.7 The sine x and cosine x plot constructed (a) without and (b) with the axis tight command

As can be seen, before the axis tight is input (Figure 3.7(a)), the x-axis limit is 8 while the maximal x value is 6.28 only; after inputting the axis tight command (Figure 3.7(b)), the right x-axis limit and the maximal x value are equal.

The xlabel, ylabel and title commands

The text for the x and y axes and that which appears at the top of the plot is provided with these commands. The desired text should be written in string form, between single quotes. The commands have the forms:

xlabel('text string')

ylabel('text string')

title('text string')

The text string can include Latin and Greek letters. The font size, name, color, style, angle of text, and some other property options can be written after the text (see below, subsection 'Formatting the text strings').

The gtext and text commands

These commands have the following form:

gtext('text string')

text(x,y,'text string')

The gtext command places the text at the x,y-location chosen by the user. After the command is entered, the Figure Window appears with two crossed lines; using the mouse, the user moves these lines to the proper point and then inputs the text by clicking the left mouse button.

The text command produces the text starting from the point of coordinates x and y.

As an example, add the title, xlabel, ylabel, text and grid commands to the commands used to construct the plot in Figure 3.2:

>> title('pH level vs Time')

>> xlabel('Time, h'),ylabel(' pH')

>> text(1.1,8.63,' pH line ') % display the pH line words at x = 2.5 and y = 6.3

>> grid

The resulting plot is shown in Figure 3.8.

f03-08-9780857094872
Figure 3.8 The tested pH level plot formatted with xlabel, ylabel, title, text, and grid commands
The legend command

This command has the following form:

legend('text string1','text string2',…,'Location', location)

It is applied to print explanations for each of the plotted curves; explanatory text should be written in 'text string1','text string2',… . The 'Location' property is optional; it specifies the area where the legend explanations should be placed, for example:

location = 'NorthEastOutside' places the legend outside the plot frames on the right;

location = 'Best' places the legend inside the plot at a better location (having the least conflict with data in plot).

The default legend location is in the upper-right corner of the plot.

For example, input the following command to add a legend to Figure 3.7:

legend('Sin x','Cos x','Location','Best')

Figure 3.9 becomes:

f03-09-9780857094872
Figure 3.9 Plot of the sin x and cos x functions with legend
Formatting the text strings

The text string in the above commands can be formatted by writing special characters (called modifiers) inside the string in the form ModifierName{ModifierValue}, or by including the property options in the command after the text string; each of these options should be written with dividing commas in the form 'PropertyName', PropertyValue.

Some useful modifiers for setting the font name, style, size, color, Greek letters, or sub- and superscripts are:

fontsize{number}specifies the size of the letters, for example, fontsize{12} sets the letter size 12.
fontname{name}specifies the name of the font in use, for example, fontname{Arial} sets the Arial font.
ame of the Greek lettersets a Greek letter, for example, sigma sets σ and Sigma sets Σ.
 it msets the bold, italic, or normal (Roman) fonts respectively.
_^sets subscripts and superscripts respectively, for example, '^oC' sets the superscript for 'o' and the resulting text is displayed as °C.

3.1.3.2 Plot editor

To format a plot interactively, there is an assortment of formatting buttons and menu items in the Figure Window. To start Plot Edit mode, click the Edit Plot button u03-01-9780857094872, located on the bar under the menu. The Figure Window menu line with the bar containing the most frequently used buttons is shown in Figure 3.10. The properties of the axes and lines, as well as the entire figure, can be changed using the pop-up menu, summoned by clicking the Edit option in the Figure menu. The title, axis labels, texts and legend can be activated using the pop-up menu, which appears after clicking the Insert option of the menu.

f03-10-9780857094872
Figure 3.10 The menu and buttons for plot editing from the Figure Window

The text, legend and other objects can be added/changed after activating 'Plot Edit' mode, by clicking on the appropriate item in the Insert menu option. Property Editor is opened using the Property Editor button or by double-clicking on the shifted curve, plotted point or axes; it provides a means for changing or editing various characteristics of the clicked object. For more detailed information see the section 'Editing Plots' in the MATLAB® documentation in the Help Window.

3.2 Generation of XYZ plots

In MATLAB®, there are three main groups of commands for presenting lines, meshes, and surfaces. These commands together with various formatting commands are described below.

3.2.1 Generation lines in three-dimensional plots

A curve in three-dimensional space is constructed from the points characterized by three coordinates each, and the lines between these points using the plot3 command. This command is similar to the plot command. The simplest shape of the command is

plot3 (x,y,z)

A more complicated form is

plot3 (x,y,z, 'Line Specifiers’,‘PropertyName', PropertyValue)

In these commands, coordinates x, y, and z should be presented as equivalent vectors with coordinates of each of the points; the Line Specifiers, PropertyName and PropertyValue have the same meaning as in the two-dimensional forms.

The grid, xlabel and ylabel commands, and analogously, the zlabel commands, can be also used to add grid and axis labels to the 3D plot.

For an example, construct a three-dimensional plot using the following commands:

>> t = 0:pi/100:6*pi;

>> x = t;

>> y = t.*sin(2*t);

>> z = t.*cos(2*t);

>> plot3(x,y,z,'k','LineWidth',4)

>> grid

>> xlabel('x'),ylabel('y'),zlabel('z')

These commands compute the parametrically given coordinates x = t, y=tsin2tsi1_e and z=tcos2tsi2_e with t changed from 0 up to 6π with step π/100. The plot3 command is used here, with the line color specifier 'k' (black) and the line property name-value 'LineWidth' -4, which increases the line width four times; other commands generate the grid and the captions to the axis.

The resulting plot appears in the Figure Window with the generated line in the shape shown in Figure 3.11.

f03-11-9780857094872
Figure 3.11 Expanding spiral line in three-dimensional coordinates

3.2.2 Mesh plots

The surface in MATLAB® can be generated by two basic commands: mesh and surf. In order to understand this, it is useful to clarify how the graphical mesh is constructed. In general, the mesh is comprised of the points (mesh nodes) and the lines between them. Every point in 3D space has three coordinates (x, y and z), which are used to reconstruct a surface. In the case of z, it is a function of the two variables x and y; it is necessary to have two two-dimensional matrices with the x- and y-values (coordinates, in terms of graphical presentation) respectively and to calculate the matrices of the z-coordinates for every (x,y)-pair.

An example of point representation in three-dimensional space is presented in Figure 3.12.

f03-12-9780857094872
Figure 3.12 Points in three-dimensional interpretation and their x,y-plane projection1

The area of the x and y coordinates for which the z coordinates must be obtained is called the domain; in the figure above, the domain represents the orthogonal grid in the x,y-plane with the limits− 2 and 2 for each of the plane axes. By writing all the x values ordered by rows (along each iso-y line), we obtain the X-matrix and an analogous procedure yields the Y-matrix (see Figure 3.12).

X=2101221012210122101221012Y=2222211111000001111122222

si3_e

Each node in the x,y-plane has a pair of x,y values. The z-coordinates are obtained for every x,y point of the domain using the element-by-element calculations. After the X, Y, and Z matrices are defined, the whole surface can be plotted.

A special meshgrid command creates the X and Y matrices from the given vectors of x and y. The command has the forms:

[X,Y] = meshgrid(x,y) or [X,Y] = meshgrid(x)

X and Y here are the matrices of the grid coordinates that determine the division of the domain that is carried out by these commands based on the given x and y vectors. The second command form is used when the x and y vectors are equal.

In the specific case of Figure 3.12, the X and Y matrices presented above can be produced using the following commands:

>> x = − 2:2;

>> [X,Y] = meshgrid(x)

X=2101221012210122101221012

si4_e

Y=2222211111000001111122222

si5_e

The command that generates the mesh with colored lines by the defined matrices X, Y and Z is

mesh(X,Y,Z)

where the X and Y matrices are defined with the meshgrid command for the given vectors x and y, and the third matrix, Z, is given for every x,y-pair or is calculated with these matrices using the given z(x,y)-expression.

As an example, plot the 3D mesh graph for the joint probability function (bivariate normal distribution) with zero-mean and standard deviations of 1:

p=12πex22y22

si6_e

where coordinates x and y are changed from -∞ to ∞, but to simplify the graphical representation define each of them between − 3 and 0 with step 0.1.

The program that plots the mesh surface reads:

>> x = − 3:0.1:0;

>> [X,Y] = meshgrid(x);

>> Z = 1/(2*pi)*exp(− X.^2/2-Y.^2/2);

>>mesh(X,Y,Z)

>>xlabel('x'),ylabel('y'),zlabel('z')

The resulting plot is shown in Figure 3.13.

f03-13-9780857094872
Figure 3.13 Mesh plot for a quarter of the bivariate distribution

3.2.3 Surface plots

The command described in the previous subsection produces a mesh with colored lines but not with colored surfaces. To generate a plot with a colored surface use the surf command, its form being

surf(X,Y,Z)

X, Y, and Z being the same matrices as in the mesh command. Use this command in the previous example as follows:

>> x = − 3:0.1:0;

>> [X,Y] = meshgrid(x);

>> Z = 1/(2*pi)*exp(− X.^2/2-Y.^2/2);

>> surf(X,Y,Z)

>>xlabel('x'),ylabel('y'),zlabel('z')

These commands generate the plot shown in Figure 3.14.

f03-14-9780857094872
Figure 3.14 Surface plot for a quarter of the bivariate distribution

Note:

 The surf and mesh commands can be used without the X and Y matrices in the form surf(Z) or mesh(Z). In this case, the Z values are plotted versus the row numbers (x-coordinates) and column numbers (y-coordinates) of the Z-matrix;

 The grid appears automatically when the surf and mesh commands are executed; the grid can be removed from the plot using the grid off command.

3.2.4 Formatting and rotating 3D plots

Many commands for 2D plot formatting, such as grid, title, xlabel, ylabel, and axis, are suitable for 3D plot formatting. In MATLAB®, there are a variety of additional commands for the formatting of a three-dimensional plot. Some of them are described below.

3.2.4.1 The colormap command

Lines, meshes and surfaces have colors. Color plays an important role in plots, especially in three-dimensional plots. By entering the mesh or surf command, color is automatically generated according to the height of surface (z-values). The colors can be set by the user using the colormap command:

colormap(c)

where c is a three-element row vector; in the triplet of color, the first element specifies red color intensity, the second, green color intensity, and the third, blue color intensity (RGB); intensities are graded from 0.0 to 1.0 and can take, for example, the following values:

c = [0 0 0]- blackc = [1 0 1] – magenta
c = [1 0 0]- redc = [0.5 0.5 0.5] – gray
c = [0 1 0]- greenc = [1 0.62 0.4] – copper
c = [0 0 1]- bluec = [0.49 1 0.83] – aquamarine
c = [0 1 1]- cyanc = [1 1 1] – white
c = [1 1 0]- yellow

For example, if the colormap([1 0 1]) command is entered after the commands that produced the bivariate distribution mesh plot in Figure 3.13, the mesh lines change in color to magenta.

Another form of this command is

colormap color_name

This form permits the introduction of names of built-in colormaps: the color_name can be jet, cool, winter, spring, and more. For example, the colormap summer changes the current colors to shades of green and yellow.

3.2.4.2 The viewpoint for 3D graph

Each 3D plot is shown in MATLAB® from a certain viewpoint. The plot orientation relative to the viewer is regulated by the view command with the form

view(azimuth,elevation)

where azimuth and elevation are the names of the two view orientation angles: the azimuth is the horizontal (x,y-plane) angle relative to the negative direction of the x-axes; the elevation angel is the vertical angle that defines the geometric height above the x,y-plane.

The observation point and view angles used in 3D plots are shown in Figure 3.15.

f03-15-9780857094872
Figure 3.15 Azimuth and elevation angles of the observation point in 3D plots

A positive azimuth angle defines the counter-clockwise direction; the positive elevation angle defines the direction of the z-axes. Both angles must be in degrees; the default values are azimuth = − 37.5°, and elevation = 30°. The various planes are generated with the chosen viewpoint angle:

 angles azimuth = 0 and elevation = 90 - top view: the x,y-projection, can be entered simply as view(2);

 angles azimuth = elevation = 0 - front view: the x,z-projection, can be entered simply as view(3);

 angles azimuth = 90 and elevation = 0 - side view: the y,z-projection;

 angles azimuth = − 37.5°, and elevation = 30° - default view;

 angles azimuth = 37.5° and elevation = 30°, mirroring the default view.

For an example, plot the bivariate probability function for bivariate t-distribution

f=12π1+x2+y2vv+22

si7_e

with degree of freedom v equals 9 and variants x and y equal 0, 0.1, …, 3 each. The commands are:

>> v = 9;x = 0:.1:3;

>> [X,Y] = meshgrid(x);

>> f = 1/(2*pi)*(1+(X.^2+Y.^2)./v). ^ (−(v+2)/2);

>> subplot(2,2,1), surf(X,Y,f)

>> xlabel('x'), ylabel('y’),zlabel(‘f’),title(‘Default view'),

>> axis tight % sets axis limits to the data range

>> subplot(2,2,2), surf(X,Y,f)

>> view(37.5,30) % azimuth = 37.5° and elevation = 30°

>> xlabel('x'), ylabel('y’),zlabel('f'),title('az = 37.5^o, el = 30^o')

>> axis tight % sets axis limits to the data range

>> subplot(2,2,3), surf(X,Y,f)

>> view(2) % azimuth = 0° and elevation = 90° - top view

>> xlabel(‘x’), ylabel(‘y’),title(‘ az = 0^o, el = 90^o’)

>> axis tight % sets axis limits to the data range

>> subplot(2,2,4), surf(X,Y,f)

>> view(3) % azimuth = 0° and elevation = 0° - front view

>> xlabel (‘x’),zlabel(‘y’), title(‘ az = 0^o, el = 0^o’)

>> axis tight % sets axis limits to the data range

The results are shown in Figure 3.16.

f03-16-9780857094872
Figure 3.16 The bivariate t-distribution function plotted with different view angles

The commands above correspond to the following steps;

 Assign the v value.

 Create vector x.

 Create grid matrices X and Y in the range of the x with the meshgrid command.

 Calculate the t-distribution function f for each pair of the X and Y values.

 Divide the page (Figure Window) into four panes and select the first pane for the first plot using the subplot command.

 Generate the first plot using the surf command at default viewpoint.

 Set the axis limits for the data range with the axis tight command.

 Select the second pane for the second plot using the subplot command.

 Generate the second plot using the surf command.

 Set the plot viewpoint to the angles to be mirrored to the default angle values using the view command.

 Set the axis limits to the data range using the axis tight command.

 Select the third pane for the third plot using the subplot command.

 Generate the third plot using the surf command.

 Set the top view angles using the view(2) command.

 Set the axis limits to the data range using the axis tight command.

 Select the fourth pane for the fourth plot using the subplot command.

 Generate the fourth plot using the surf command.

 Set front view angles with the view(3) command.

 Set axis limits to the data range using the axis tight command.

3.2.4.3 The 3D plot rotation

A generated plot can be rotated using the mouse after pressing the 'rotate

3D' button, u03-02-9780857094872, in the Figure Window toolbar; the azimuth, Az, and the elevation, El, angle values simultaneously appear in the bottom-left corner of the window. A plot view of the rotation regime is shown in Figure 3.17.

f03-17-9780857094872
Figure 3.17 The Figure Window with a plot in the rotation regime

The rotation regime can also be set using the rotate3d on command. After typing and entering the command in the Command Window, execute the following:

 Go to the Figure Window.

 By holding the mouse button and moving the mouse, we can rotate the plot and view the azimuth az and elevation el values that appear.

The regime can be interrupted after entering the rotate3d off command.

3.3 Specialized two- and three-dimensional plots

Among the 2D and 3D graphs used by quality assurance specialists are histograms, Pareto charts, scatter plots, logarithmical plots, plots with error boundaries for each x,y point and some others. These graphs are constructed using specialized commands. Some of these graphs, together with a list of additional graphic commands, are described briefly below.

3.3.1 Plotting a histogram

A histogram is one of the most popular bar graphs used in the field of quality assurance and statistical analysis of data. To construct a histogram, the total data range is divided into several equal sub-intervals called bins, after which the number of data falling into each of these intervals is counted. These values are called frequencies and are presented as bar heights; the sub-intervals are presented as bar widths. A histogram is plotted using the hist command. The simplest form of this command is

hist(y),

where y is the vector containing the data points. This command generates a graph of bins that present the numbers of the data points in each of the 10 (default) equally-spaced bins.

For example, at an experimental site, the heights (in meters) of 29 black cherry trees were: 21.9, 24.4, 22.5, 24.0, 24.6, 26.2, 30.7, 24.4, 26.0, 21.4, 23.3, 27.8, 28.5, 29.8, 24.3, 22.6, 29.0, 20.3, 21.1, 26.5, 18.8, 25.8, 32.3, 24.6, 24.2, 24.0, 22.0, 27.7 and 27.0. To plot a histogram based on these data, enter the following commands:

>> y = [21.9 24.4 22.5 24.0 24.6 26.2 30.7 24.4 26.0 21.4 23.3 27.8 28.5 29.8 24.3 22.6 29.0 20.3 21.1 26.5 18.8 25.8 32.3 24.6 24.2 24.0 22.0, 27.7 27.0];

>> hist(y)

>> xlabel('Tree height, m'),ylabel('Number of heights per one bin')

The resulting plot is shown in Figure 3.18.

f03-18-9780857094872
Figure 3.18 Histogram plot of the tree height data

Another form of the hist command is

n = hist(y)

that outputs the n vector with the numbers of data points falling to each of the bins. Note: this command yields a numerical output but does not plot a histogram.

Using the n = hist(y) command for the example above, the following frequencies can be displayed in the Command Window:

>> n = hist(y) n =

n=1344543221

There are additional forms of the hist command that can be applied to define bin locations or to input desired x values for the bin centers; for more detailed information enter the help hist command in the Command Window.

3.3.2 Pareto chart

Along with the histogram, the Pareto chart is one of the most well-known quality assurance tools. This chart ranks causes - from the most to the least significant; the values of these causes are represented by bars and by a line of the cumulative total percentage. The simplest form of the command is

pareto(y,y_names)

where y is a vector with values that should be ranked and y_names is a string matrix representing names associated with each of the y-values.

Let us, for example, generate a Pareto chart for the following number of defects and their causes that were observed in printed circuit boards (PCB) manufactured by one of the production lines: 400 defects due to insufficient solders, 30 due to metal traces that did not meet confirmed specification, 100 due to broken buried metal lines, 20 due to component misalignments and 10 due to miscellaneous causes. The commands used to generate the Pareto chart (see Figure 3.19) are:

>>y = [400 30 100 20 10]; % vector with observed defect numbers

>>y_names = strvcat('solders', 'traces', 'metal', 'misalignments', 'others'),

%matrix of shortened names

>> pareto(y,y_names)

>> title('PCB defect causes rank')

f03-19-9780857094872
Figure 3.19 Pareto chart with ranked PCB defects

Note: only the first 95% of the ranked y-values are displayed in a MATLAB® Pareto chart.

3.3.3 Plot with error bars

Values of tested parameters frequently contain observational errors that should be shown in graph form. The errorbar command plots observed values with error limits. The simplest form of this command is

errorbar(x,y,l,u)

where x and y are the vectors of observed values, l and u are the vectors with the lower and upper errors respectively.

For an example, generate a plot showing the pH level data measured for quality assurance of a pharmaceutical drug (see data in Section 3.1, p. 68). The upper error is 0.15 and the lower, 0.075 pH at each point. Entering the following commands yields the plot in Figure 3.20:

>> t = 0:.5:5; % vector with the time data

>> pH = [8.32 8.44 8.46 8.49 8.76 8.79 8.40 8.4 8.60 8.65 8.86];

% pH data

>> u = 0.15+zeros(1,length(pH)); % creates vector with upper errors

>> l = u/2; % creates vector with lower errors

>> errorbar(t,pH,l,u) % generates plot with different lower and % upper errors

>> xlabel('Time, hour'),ylabel('pH level')

>> title('Data with asymmetric errors'),grid

f03-20-9780857094872
Figure 3.20 Plot of pH level data with error bars

Line style and/or marker specifiers may be included in the errorbar command to format the line color and style, and marker; for example, the errorbar(t,pH,l,u,'-o') command changes a whole line to a dashed line and assigns circles to the data points into the previous plot.

When the data have symmetric errors, the errorbar command can be used with a single error vector; in our example, with an upper and lower error of 0.075, the appropriate command is errorbar(t,pH,l).

3.3.4 Scatter plot

Similar to histogram and Pareto graphs, the scatter plot is used to study quality characteristics. The simplest command for 2D scatter plotting of data is

scatter(x,y,'filled')

where x and y are vectors of the same length; the 'filled' specifier is optional and fills the marker, when written.

For an example, generate a scatter plot for a test device that displays a response with the following values of certain quality characteristic: 100.89, 100.36, 98.60, 99.07, 99.91, 98.62, 100.39, 96.88, 100.38, 97.53, 101.78, 98.63, 99.11, 98.62, 98.59, 99.06, 99.97, 99.09, 98.97, 98.69, 99.77, 98.79, 95.95, 97.52, 97.08, 96.59, 98.21, 98.69, 98.54, 97.74, 97.25, 97.65, 98.70, 99.77, 97.02, 94.92, 97.65, 96.46, 95.25, 95.39, 94.65, 93.15, 95.36, 95.05, 95.83, 94.44, 94.97, 96.85, 93.95, 93.36, 97.43, 94.09; the response was observed for 17 minutes with intervals of 0.3333 minutes. The following commands yield the scatter plot in Figure 3.21:

>> x = 0:0.3333:17;

>> y = [100.89,100.36,98.60,99.07,99.91,98.62,100.39,96.88,100.

38,97.53,101.78,98.63,99.11,98.62,98.59,99.06,99.97,99.09,98.

97,98.69,99.77,98.79,95.95,97.52,97.08,96.59,98.21,98.69,98.

54,97.74,97.25,97.65,98.70,99.77,97.02,94.92,97.65,96.46,95.

25,95.39,94.65,93.15,95.36,95.05,95.83,94.44,94.97,96.85,93.

95,93.36,97.43,94.09];

>> scatter(x,y,'filled')

>> xlabel('Time, min'),ylabel('Quality characteristics')

>> title('Scatterplot for quality characteristics')

f03-21-9780857094872
Figure 3.21 Scatterplot for quality characteristics

The same plot can also be generated with the plot command, but the scatter command has other forms that make it preferable; for instance, when we want to change the marker area (in square points, one point = 1/72 inch) and color of each of the points. One of such forms is

scatter(x,y,s,'filled')

where, in addition to the preceding form, the s is a vector for defining the marker area in each point; s can be given as scalar for plotting the same size of all the markers. Entering the scatter(x,y,100,'filled') command in the example presented here produces the plot in Figure 3.22 with the 100 point2 marker area for each of the data points.

f03-22-9780857094872
Figure 3.22 Scatterplot with enlarged marker area

For detailed information about available forms of the scatter command, enter the doc scatter command from the Command Window.

3.3.5 Supplementary commands for two- and three-dimensional graphics

There are additional commands available for 2D and 3D plotting. A complete list can be obtained by entering the following commands in the Command Window: help graph2d, help graph3d or help specgraph. Table 3.3 presents further commands for two- and three-dimensional plotting that can be useful for graphic presentation in quality analyses; the table provides the form of the corresponding basic command with short explanations, examples and the resulting plots.

Table 3.3

Additional commands and plots for 2D and 3D graphics*

CommandsExamplesPlots
figure
generates a new figure window;
figure(h)
generates a Figure Window with number h, or assignsthe existing Figure Window with number h.
>>figure(2)u03-03-9780857094872
fplot('function',limits)
plots a function y=f(x) with specified x-limits (the limitsof y-axis may be added).
>> fplot('exp(.l*x)',[10,60])u03-04-9780857094872
polar(theta,rho)
generates a plot in polar coordinates in which theta andrho are the angle and radius respectively.
>>th = linspace(0,2*pi,150);
>> r = 4*cos(3,tth);
>> polar(th,r)
u03-05-9780857094872
semilogy(x,y,'LineSpec')
generates a semi-logarithmic, x,log(y)-plot with the'LineSpec' specification for the marker, line and/or coloranalogously to the plot command.
>>x = [298.15 306.15 318.15 328.15];
>>y = [120.14 55.45 19.92 8.95];
>> semilogy(x, y,'-o')
>> axis tight, grid
u03-06-9780857094872
loglog(x,y)
generates a plot with a log scaled (base 10) on both the x- and the y-axes.
>> x = linspace(0.1,20,100);
>> y = 5 + exp(− 0.5*x);
>> glog(x,y)
u03-07-9780857094872
sphere or sphere(n)
plots a sphere with 20 or n mesh cells respectively.
>> sphere(40),axis equalu03-08-9780857094872
box on
draws a box around the plot;
box off
removes the drawn box from the plot.
>> sphere(40),axis equal
>> box on
u03-09-9780857094872
cylinder or cylinder(r)
draws an ordinary and a profiled cylinder with the profilegiven by the r expression.
>> t = 0:pi/10:2*pi;
>> r = atan(t);
>> cylinder(r)
u03-10-9780857094872
contour(X,Y,Z,v)
displays the isolines of matrix Z in the
x,y-plane;
Z is interpreted as height with respect to the x,y-plane, v is the number of contour lines, or the vector specifying the contour lines.
>> x = − 2:.2:2;
>> [X,Y] = meshgrid(x);
>> Z = X.*exp(− X. ^2-Y.^2);
>> contour(X,Y,Z,7);
>>% Or with level values
>> c = contourf X,Y,Z,7);
u03-11-9780857094872
The form c = contour(X,Y,Z,n)
with clabel(c) displays the level values c of the isolines.
>> clabel(c)u03-12-9780857094872
contour3(X,Y,Z,n)
displays the isolines of matrix Z in the x,y-plane;
Z is interpreted as the height with respect to the x,y-plane,
n as the number of contour lines.
>> x = − 2:.2:2;
>> [X,Y] = meshgrid(x);
>> Z = X.*exp(− X. ^2-Y.^2);
>> contour3(X,Y,Z,7);
u03-13-9780857094872
surfc(X,Y,Z)
generates surface and contour plots together.
>> x = − 2:.2:2;
>> [X,Y] = meshgrid(x);
>> Z = X."exp(− X.^2-Y. ^2);
>> surfc(Z);
u03-14-9780857094872
bar(x,y)
displays the values in a vector or matrix as vertical bars.
>> x = 55:5:100;
>>y = [1,2,1,0,1,4,3,3,5,5];
>> bar(x,y)
>> xlabel('Grades')
>> ylabel( 'Number of grades per bin')
u03-15-9780857094872
barh(x,y)
displays the values in a vector or matrix as horizontal bars.
>> x = 55:5:100;
>>y = [1,2,1,0,1,4,3,3,5,5];
>> barh(x,y)
>> xlabel(''Number of grades per bin')
>> ylabel('Grades')
u03-16-9780857094872
bar3(Y)
generates 3D-bar plot data grouped in columns.
>> Y = [2 3.4 7.1 2.2 1;3 6 4.1 3 2;0.3 5 6.3 4 2];
>> bar3(Y)
u03-17-9780857094872
hist3(x,n)
generates a bivariate histogram; x is a two-column matrix of data, n is a two-elements vector of the n(l)-by-n(2) bins.
>> x = randn(100,2);
>> hist3(x,[5 5])
u03-18-9780857094872
stem(x,y)
displays data as lines extending from a baseline along the x-axis. A circle (default) terminates each stem.
>> x = 55:5:100;
>>y = [1,2,1,0,1,4,3,3,5,5];
>> stem(x,y)
>> xlabel('Grades'),
>> ylabelf 'Number of grades per bin')
u03-19-9780857094872
stem3(x,y,z)
generates a 3D boxed plot with lines from the x,y-plane to the z value terminated by a circle (default). The x, y, and z coordinates must be vectors or matrices of the same size.
>> x = 0:0.5:2;
>> [X,Y] = meshgrid(x);
>> z = X.'Y./(X + Y);
>> stem3(X,Y,z)
u03-20-9780857094872
stairs(x,y)
generates a stairs-like plot of the discrete y data given at the specified x points.
>> x = 1900:20:2000;
>>y = [76 106 132 179 111 249];
>> stairs(x,y)
>> xlabel('Year'),
>> ylabel('People, min')
u03-21-9780857094872
pie(x)
draws a pie chart using the data in x. Each element in x is represented as a slice.
>> x = [56 68 42 91 100];
>> pie(x)
>> title('Group grades')
u03-22-9780857094872
pie3(x,explode)
generates a pie chart; explode specifies an offset of a slice from the center of the chart; explode is a vector of the same length as x, in which 1 denotes an offsetted slice and 0 a plain slice.
>> x = [56 68 42 91 100];
>> explode = [0 1 0 0 0];
>> pie3(x,explode)
>> title('Group grades')
u03-23-9780857094872

t0020_at0020_bt0020_ct0020_d

* The commands are described in their simplest form.

For more complicated possibilities of this command see application example 3.4.7.

3.4 Application examples

3.4.1 X-bar control chart

In this chart, a measured process characteristic is plotted together with the upper and lower control limits in order to assure the mean value. Say we have the N = 15 averaged X-values of the some characteristic: 9.42, 9.39, 10.15, 10.55, 10.79, 9.51, 10.21, 10.05, 9.32, 9.84, 9.56, 10.57, 9.80, 10.15 and 9.57; the upper and lower control limits, UCL and LCL, of the overall mean are X¯±3σsi8_e, 10.9 and 9.3 respectively.

Problem: Generate a plot with X-values with the central line as X-mean, ±σ/√N, standard error lines, and the upper and lower control limits. Mark the X values with the point marker and add a solid line between them; draw the standard error and control limit lines as a dash-dot and a dotted line, respectively; add captions to the control limit lines and to the plot.

The commands for this presentation are:

X = [9.42,9.39,10.15,10.55,10.79,9.51,10.21,10.05,9.32,9.84, 9.56,10.57,9.80,10.15,9.57];% measured values
A3 = 1.63;% A3 factor
StDev=0.57;%averaged standard deviation
N=length(X);% X length
n=1:N;% vector of subgroup numbers
aver_X=mean(X);% X mean
UCL=aver_X+A3*StDev;% upper control limit
LCL=aver_X-A3*StDev;% lower control limit
x_l=[1 N];% x-for all horizontal lines
y_aver=[aver_X aver_X];% y-coordinates of mean line
y_UCL=[UCL UCL];y_LCL = [LCL LCL];% y-coord-s of CL

% ============= Chart generation commands ===========

plot(n,X,'.-',x_l,y_aver,'-',x_l,y_UCL,'--r',x_l,y_LCL,'--r')

axis([1 N min([X LCL]-0.2) max([X UCL]) + 0.2]);

xlabel('Unit')

ylabel('Quality characteristic')

title('Control chart')

text(N-2,UCL+0.05,'UCL')% x- text for UCL

text(N-2,LCL-0.05,'LCL')% x- text for LCL

The plot created by these commands is (Figure 3.23) :

f03-23-9780857094872
Figure 3.23 x-bar control chart

The UCL, LCL, center and error lines of this plot were created using the plot command by inputting two extreme x, 1 and N, and two y-coordinates for the standard errors and control limits.

The axis command sets the following axis limits for the graph: x-limits, in accordance with the extreme sample numbers, and y-limits, in accordance with the minimal X and LCL values and maximal X and UCL values; to create y-margins, the value 0.1 must be added to the positive extreme value and then subtracted from the negative extreme value.

The text commands add captions to the UCL and LCL lines.

Note, there is a specialized command for control chart construction in the Statistics Toolbox™. This command is described in Chapter 4.

3.4.2 Deriving the most important defect causes with the 80–20 Pareto principle

This principle, in terms of quality improvement, states that 80% of the problems are produced by 20% of the causes. Use here the data for PCB presented in Subsection 3.3.3 with four additionally detected defect number-name data: 12 - thermal deformation, 15 - plate stratification, 32 - cracks, 8 - spots of solder.

Problem: Plot a Pareto chart with an 80% line, mark it in red and display the main defect cases names in the Command Window; add a grid and a title to the plot.

The commands for solving this problem are:

>> y = [400 30 100 20 10 12 15 32 8];%defect occurrences
>> y_names = strvcat('solders','traces','metal',%matrix of shortened
'misalignments','others','deformation',%names
'stratification','cracks','spots'),
>> pareto(y,y_names), hold on >>
plot([0 length(y)], [0.8 0.8]*sum(y), '-r')
>> title('PCB defect cause rank'),hold off
>> [y_sort,ind]=sort(y,2,'descend'),% y in descend order
>> y_perc=cumsum(y_sort)*100/sum(y);% cumulative sum, % in percentages
>> causes=y_perc<=80;% less than 80 % percentages
>> y_names=y_names(ind,:);% causes sorted as % y_sort
>> disp('Defect Percentage')
>> disp([y_names(causes,:) num2str(y_sort(causes)')])

The generated plot (Figure 3.24) and the results are:

f03-24-9780857094872
Figure 3.24 Pareto chart of the PCB defect causes
DefectPercentage
Solders400
Metal100

The hold on command was used after the pareto command to add the 80% line. Two y-coordinates for this line were defined as [0.8 0.8]*sum(y), where sum(y) presents the y-scale upper limit. The commands following the hold off command are used for:

 [y_sort,ind]=sort(y,2,'descend') sorts the y (defect quantities) coordinates along columns in descending order and returns the sorted defect numbers and their location numbers to the y_sort and ind vectors respectively;

 y_names=y_names(ind,:) rearranges the defect names according to ind;

 disp([y_names(causes,:) num2str(y_sort(causes)')]) displays defect causes together with percentages in the Command Window.

3.4.3 Histogram with specification limits

An extrusion process has a target of 46.00 and frequencies of 1, 5, 11, 15, 18, 17, 14, 11, 4, and 1 that fall in ten equidistant intervals between 41 and 51.The upper and lower specification limits USL and LSL for this process are 50.50 and 41.50 respectively.

Problem: Generate two plots in a single Figure Window: (a) with a histogram; and (b) the same histogram with a vertical target line with a five-point width in green and USL and LSL vertical lines in red. Add captions to the lines and a title to the plot.

The commands used to solve this problem are:

>> target=46.00;

>> USL=50.5;LSL=41.5;

>> y=[1 5 11 15 18 17 14 11 4 1];

>> x=linspace(41,51,10);

>> subplot(1,2,1)

>> bar(x,y)

>> xlabel('Value'),ylabel('Frequency')

>> subplot(1,2,2)

>> bar(x,y)

>> xlabel('Value'),ylabel('Frequency')

>> hold on

>> plot([41.5 41.5],[0 max(y)], '-r',[50.5 50.5],[0 max(y)], '-r')

>> plot([target target],[0 max(y)],,-g,,'LineWidth',5)

>> hold off

>> text(41.8,15, 'LSL'),text(50.8,15, 'USL'),text(46.3,17.7, ' Target')

The resulting plot (Figure 3.25) is:

f03-25-9780857094872
Figure 3.25 Histogram with and without spécification limits

Note: both these histograms are constructed using the bar command and not with the hist command, as the latter uses original values and not frequencies of these values, as is necessary in the present problem.

3.4.4 Bivariate normal distribution with correlated variables

One- and bivariate normal (Gaussian) distributions are widely used when a two-variant analysis is necessary. In general, a two-dimensional probability density function, f(x, y) of the bivariate normal distribution of the two variates x and y is given by

fxy=12πσxσy1ρ2exμx22σx2+yμy22σy2ρxμxyμyσxσy

si9_e

where μx and μy are the mean values of the x- and y-variates respectively, σx and σy are those of the variate deviations and ρ is the correlation coefficient.

Problem: Calculate and plot the distribution function for μx= 60, μy= 90, σx= 4, σy= 6, ρ=0.1 in x-axis limits μx ± 3σx and y-axis limits μy ± 3σy.

To solve this problem carry out the following steps:

 Assign values to μx, μy, σx, σy, and ρ.

 Calculate boundaries for x and y as x = μx ± 3σx and y = μy ± 3σy.

 Define the 40-point vectors x and y with the linspace command.

 Create an X,Y grid in the ranges of the x, y vectors by using the meshgrid command.

 Calculate f by the above expression.

 Generate an X,Y,f plot using the surf command.

 Set plot axes for the previously calculated boundaries using the axis tight command.

The commands are:

>> mux=60; muy=90;
>> sigmax=4; sigmay=6;ro=.1;
>> xlim=3*sigmax; ylim=3*sigmay;% setting limits for x, y
>> xmin=mux-xlim;xmax=mux+xlim;
>> ymin=muy-ylim;ymax=muy+ylim;
>> x=linspace(xmin,xmax,40);% defining vector x
>> y=linspace(ymin,ymax,40);% defining vector y
>> [X,Y]=meshgrid(x,y);% creates X,Y grid from % the x,y vectors
>> r1=(X-mux).^2/(2*sigmax^2);
>> r2=(Y-muy). ^2/(2*sigmay^2);
>> r3=(X-mux).* (Y-muy)/(sigmax*sigmay);
>> f = 1/(2*pi*sigmax*sigmay*sqrt(1-ro^2))*exp(−(r1+r2-ro*r3)/ (1-ro^2));% calculate f
>> surf(X,Y,f)% generates surface graph
>> xlabel('x'),ylabel('y'),zlabel('f(x,y)')
>> axis tight% set axis to the x and y % variate limites

The figure generated (Figure 3.26) is

f03-26-9780857094872
Figure 3.26 Surface plot of a bivariate normal distribution

3.4.5 Histogram for the bivariate data

In quality control with two tested quality characteristics, it is sometimes desirable to construct a bivariate histogram. Assume we have the following inspection data for 50 compression piston rings:

 gap, s, in mm: 0.67, 0.58, 0.36, 0.61, 0.48, 0.55, 0.04, 0.09, 0.27, 0.43, 0.74, 0.31, 0.78, 0.54, 0.75, 0.44, 0.20, 0.48, 0.45, 0.65, 0.31, 0.24, 0.31, 0.07, 0.25, 0.35, 0.41, 0.38, 0.58, 0.43, 0.94, 0.49, 0.94, 0.18, 0.56, 0.32, 0.58, 0.58, 0.43, 0.00, 0.53, 0.52, 0.84, 0.30, 0.64, 0.56, 0.08, 0.52, 0.17, 0.8; and

 mean radial pressure, p, in MPa: 0.20, 0.45, 0.14, 0.29, 0.19, 0.10, 0.05, 0.29, 0.19, 0.03, 0.11, 0.24, 0.05, 0.35, 0.10, 0.47, 0.04, 0.23, 0.03, 0.09, 0.11, 0.26, 0.34, 0.25, 0.14, 0.32, 0.32, 0.22, 0.29, 0.26, 0.05, 0.31, 0.10, 0.11, 0.23, 0.15, 0.18, 0.29, 0.36, 0.17, 0.25, 0.16, 0.23, 0.27, 0.11, 0.24, 0.29, 0.21, 0.46, 0.11.

Problem: Generate a bivariate histogram using the hist3 command and present it using the azimuth and elevation angles equal to − 128 and 46 degrees respectively.

The following steps should be taken:

 Create two vectors with s and p values.

 Generate two column matrices including vectors s and p.

 Generate a 3D histogram with 4×4 bins.

 Set the required viewpoint for the generated plot.

The commands that solve this problem (Figure 3.27) are:

>> s = [0.67 0.58 0.36 0.61 0.48 0.55 0.46 0.09 0.27 0.43 0.74 0.31 0.78 0.54 0.75 0.44 0.20 0.48 0.45 0.65 0.31 0.24 0.31 0.07 0.25 0.35 0.41 0.38 0.58 0.43 0.94 0.49 0.94 0.18 0.56 0.32 0.58 0.58 0.43 0.00 0.53 0.52 0.84 0.30 0.64 0.56 0.08 0.52 0.17 0.8];

>> p = [0.20 0.45 0.14 0.29 0.19 0.10 0.05 0.29 0.19 0.03 0.11 0.24 0.05 0.35 0.10 0.47 0.04 0.23 0.03 0.09 0.11 0.26 0.34 0.25 0.14 0.32 0.32 0.22 0.29 0.26 0.05 0.31 0.10 0.11 0.23 0.15 0.18 0.29 0.36 0.17 0.25 0.16 0.23 0.27 0.11 0.24 0.29 0.21 0.46 0.11];

>> M=[s' p']; % generates two columns matrix

>> hist3(M,[4 4]) % generates bivariate histogram with 4×4

% bins

>> xlabel('Piston gap, mm'), ylabel('Mean Radial Pressure, MPa'),

>> zlabel('Frequency, unit')

>> title('Histogram of the bivariate date')

>> view(− 128,46) % az = − 128° el = 46

f03-27-9780857094872
Figure 3.27 Bivaraiate histogram for the piston ring data

3.4.6 The measure of leanness of a person

Quality of life is based on a set of indicators that reflect the health of an individual. These indicators are not yet standardized. One of the possible health indicators is the Ponderal Index (PI) that characterizes the relationship between body weight m and body height h. The expression is

PI=mh3

si10_e

where m is weight in kg and h is height in m, and PI in kg/m3.

Problem: Calculate PI and generate a three-dimensional surface plot in which m and h are the horizontal coordinates and PI are vertical coordinates; the m values are 40, 50, …, 160 kg, and the h values are 1.45, 1.55, …, 2 m. Set the viewpoint of the plot to azimuth − 138° and elevation 26°.

Use the following steps to solve the problem:

 Input the weight and height values in the m and h vectors.

 Create X,Y grid matrices in the ranges of the m and h vectors respectively using the meshgrid command.

 Calculate PI using the above expression.

 Generate a 3D plot using the determined X,Y,PI-values.

 Set the required viewpoint using the view command.

The generated (Figure 3.28) plot and commands that solve this problem are:

f03-28-9780857094872
Figure 3.28 Ponderal index surface plot
>> m = 40:10:160;h=1.45:0.05:2;
>> [X,Y] = meshgrid(m,h);% creates X,Y grid from the x,t
% vectors
>> PI=X./Y.^3;% calculate element-wise the PI
>> surf(X,Y,PI);% plot surface graph
>> xlabel('Weight, kg'),ylabel('Height, m')
>> zlabel('Ponderal Index, kg/m^3')
>> view(− 138,38)% az = − 138° el = 38

3.4.7 Gantt chart

A Gantt chart is a horizontal bar plot that illustrates a project schedule, used to track project tasks.

Problem: Generate a Gantt chart for a project that has five tasks, each with the following start dates: 17/01/13, 21/02/13, 01/02/13, 01/03/13 and 01/04/13, and task durations of 6, 10, 50, 90, and 120 days respectively. Display the start and finish date for each task.

Follow these steps to solve this problem:

 Input the task start dates in a column using the format 'dd/mm/yy' (dd - day number, mm - month number, yy - year number) and a numeric vector with task durations.

 Convert the start dates from strings to numeric format with the datenum command.

 Calculate the finish dates with the addtodate command.

 Create a matrix with two rows: the first with the start dates and the second with the finish dates.

 Generate a horizontal bar plot with the barh command and its 'stacked' option that displays one bar for each of the date matrix rows and shows with colors the relative contribution each row elements.

 Hold the plot and use the new barh command for bars of the start dates that colors the bars ('w') and their edges ('EdgeColor','w') in white.

 Use the disp command to display the captions and two columns for the start and finish dates, with the finish dates formatted as 'dd/mm/ yy' with two spaces before dd to separate the start and finish dates in the date table.

The commands, the resulting table and the generated Gantt chart (Figure 3.29) are:

>>task=1:5;

>>sta=['17/01/13';'21/01/13';'01/02/13';'01/03/13';'01/04/13'];

>>days = [6 10 50 90 120];

>>t_start = datenum(sta,'dd/mm/yy'), % converts start dates to % numeric format

>>t_d_start(1)=0;

>>for i=1:length(days)

t_end(i,:)=addtodate(t_start(i,:), days(i), 'day'), % calculates the % finish date

% calculate start dates beginning from the 0s month t_d_start(i)=t_start(i)-t_start(1); end

>>t_bar=[t_d_start' t_end-t_start];% prepare matrix for staked % (two-parts) bars

>>barh(t_bar(1:end,:),'stacked')

>>hold on

>>% clear by white color the before-start-bars

>>barh(t_bar(1:end,1),'w','EdgeColor','w')

>>plot([0 0],[0 max(task)+1],'k')% paints the left axis of the plot in % black

>>hold off

>>xlabel('Time, days from start'),ylabel('Task number')

>>title('Gantt chart')

>>disp(' Start Finish')

>>disp([sta,datestr(t_end,' dd/mm/yy')]) % displays the start and % finish dates

f03-29-9780857094872
Figure 3.29 Gantt chart for project with 5 tasks
StartFinish
17/01/1323/01/13
21/01/1331/01/13
01/02/1323/03/13
01/03/1330/05/13
01/04/1330/07/13

3.5 Questions for self-checking

1. Which sign or word specifies an upright triangular marker that designates a point on the plot: (a) +, (b) the word 'circle', (c) ^, (d) t?

2. In a three-dimensional graph the mesh command generates: (a) a surface, (b) a surface mesh, (c) a line?

3. To place several plots on the same page, i.e. in the same Figure Window, it is necessary to divide the page using the following command: (a) hold on, (b) plot(x1,y1,x2,y2, …), (c) subplot?

4. To produce a plot without an axis it is necessary to use the following command: (a) hold off, (b) grid off, (c) axis off?

5. The hist command plots bars with heights that are equal to: (a) frequencies of data, (b) data values, (c) possibly both options (a) and (b)?

6. The 2D graph with data points lacking a line between them can be produced using the following command: (a) plot, (b) scatter, (c) both options (a) and (b) are correct, (d) there is no correct answer?

7. A bivariate bar plot for two quality characteristics given by their frequencies can be produced using the following command: (a) bar3, (b) hist3, (c) scatter3, (d) plot3?

8. How do you set the required viewpoint in order to generate the plot: (a) rotate the plot with the mouse, (b) write and input the appropriate view command, (c) both answers are correct?

3.6 Answers to selected questions

2. (b) a surface mesh.

4. (c) axis off.

6. (c) both options (a) and (b) are correct.

8. (b) write and input the appropriate view command.


1 Generated with the stem3(x,y,z) command; used expression z = 8 + x + y.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.199.210