Using MATLAB to Visualize Scientific Data¶
Introduction¶
MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in common mathematical notation. MATLAB is an interactive system whose basic data type is the array or matrix.
MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. It includes high-level functions for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. There are two basic ways to create graphs in MATLAB. You can either use the MATLAB GUI plotting tools to interactively create graphs (see Some Ways to Use Plotting Tools for more information) or you can use the command interface by entering MATLAB graphics commands in the Command Window.
In this tutorial we will use the command interface to show how to visualize scientific data using MATLAB graphics commands. We will cover major visualization techniques such as slicing, color mapping, contouring, oriented glyphs, and streamlines. It is assumed that the student is familiar with the basics of using MATLAB.
For an introductory tutorial on using MATLAB, see the SCV tutorial an Introduction to MATLAB. MathWorks, the developer of MATLAB, also has extensive MATLAB documentation including video tutorials on its website. And there is a full set of documentation available from within MATLAB itself which can be viewed by selecting Product Help from the Help menu.
Getting started¶
The most effective way for you to go through this tutorial is to run the listed example code in a MATLAB session as you proceed through the tutorial. This can be accomplished by copying and pasting the listed example code into the MATLAB Command Window. It will also be helpful for you to browse the MATLAB documentation for the specific functions as we discuss them (links are provided). After browsing the documentation, you should then experiment with the example code by varying some of the arguments and watching the effect this has on the output. By playing with the example code, you will gain a deeper understanding of how the various graphic functions work.
Boston University SCV users, please go to the SCV MATLAB Help Page for information specific to the installation at this site. This will tell you on what machines MATLAB is available, how to set up your environment, how to set your display, and where the documentation is.
Graphics Model¶
MATLAB has an abstract graphics layer above the local host’s graphic software interface. This insures cross-platform portability and creates a device independent graphics layer. In MATLAB graphics objects are used to create visual representations of data. There are two basic types of graphics objects in the MATLAB graphics model: Core graphics objects and Composite graphics objects. Core graphics objects include basic drawing primitives such as line, text, rectangles, patches (filled polygons), surfaces (3D grid of vertices), images (2D matrix representation of an image), light sources, and axes (define the coordinate system). Composite graphics objects are composed of core graphics objects that have been grouped together to provide a more convenient interface.
Creating a Graphics Window  
In order to visualize your data, you will need a graphics window which contains a figure, an axes, and a view.
Figure¶
All MATLAB graphical output is directed to a window that is separate from the Command Window. This window is referred to as a figure. Figures can contain menus, toolbars, user-interface objects, context menus, axes, or any other type of graphics object. MATLAB functions that generate graphics output such as plot, surf, slice, etc. will create a figure if none already exists. If a figure does exist, then these functions will display their graphics output in the current figure window (the last figure window used or clicked in). By default this will be done without clearing or resetting the current figure properties.
To create a new figure, use the figure function. Here is example code to create a simple graphics window:
figure
Every graphics object has a set of properties associated with it. These
properties define the different attributes of an object, such as its
color, size, position, etc. Properties are usually specified by
name/property pairs e.g. figure(
'PropertyName', propertyvalue, ...
). These properties can be set
either at the time of creation by specifying property name and property
value pairs or after the graphics object has been created by using the
set
function.
When creating a new figure, MATLAB creates a window whose characteristics are specified by your computer’s windowing system, by the default MATLAB figure properties, and by the properties specified as arguments to the function. Any property not specified as an argument will use the default values. See the Figure Properties for a list of properties that can be set for a figure.
Here is an example of setting figure properties to create a new window named ‘Test Window’ with no menus and with a screen position of [left 100, bottom 500, width 250, height 250]:
figure('Name','Test Window','Position',[100 500 350 350],'MenuBar','none')
You can use clf (clear figure) to clear the contents of the current figure and reset all of its properties to their default values.
clf reset
Axes¶
Axes define a frame of reference for the display objects in the figure window. This frame of reference is the coordinate system which defines where each data point is placed on the graph. Axes orient and scale graphical output to produce the view of the data that you see on screen. By default, the size of the axes MATLAB creates is normalized to the size of the figure window. All functions that draw graphics create an axes object if one does not already exist.
As with figure properties, axes properties are used to specify the characteristics of the axes. The Axes Properties list all axes properties and provide an overview of the characteristics that are affected by each property. For example camera properties such as the camera position, camera target, up vector, and view angle can all be directly set with axes properties. The axes function, however, is a low-level function. Though you can specify values for these properties directly, it is much easier to use the view function (covered in the next section) to set up the axes using default property values and to define a reasonable view.
View¶
The view is the particular orientation you set to display the visualization. The term viewing refers to the process of displaying a graphical scene from various directions by adjusting the camera position, changing the perspective, changing the aspect ratio, etc.
MATLAB viewing is composed of two basic areas:
Positioning the viewpoint to orient the scene
Setting the aspect ratio and relative axis scaling to control the shape of the objects being displayed
Positioning the viewpoint: The view function specifies the viewpoint by defining azimuth and elevation with respect to the axis origin. Azimuth is a polar angle in the x-y plane, with positive angles indicating counterclockwise rotation of the viewpoint. Elevation is the angle above (positive angle) or below (negative angle) the x-y plane.
MATLAB automatically selects a viewpoint that is determined by whether the plot is 2-D or 3-D:
For 2-D plots, the default is azimuth = 0┬░ and elevation = 90┬░.
For 3-D plots, the default is azimuth = -37.5┬░ and elevation = 30┬░.
view(2)
sets the default two-dimensional view, with az = 0, el =
90.view(3)
sets the default three-dimensional view, with az = ΓÇô37.5,
el = 30.view(az,el)
or view([az,el])
set the viewing angle for a
three-dimensional plot.The azimuth, az, is the horizontal rotation about the z-axis as measured in degrees from the negative y-axis. Positive values indicate counterclockwise rotation of the viewpoint. el is the vertical elevation of the viewpoint in degrees. Positive values of elevation correspond to moving above the object; negative values correspond to moving below the object.
Here is example code that creates a simple graphics window with a default axes, a view, and a surface:
Z = peaks(20);
figure;
h = surf(Z);
view([-20,25]);
Setting the aspect ratio and axis scale: The axis command enables you to adjust the aspect ratio of graphs. The axis command also enables you to adjust the scaling of graphs. Normally MATLAB stretches the axes to fill the window and chooses appropriate axes ranges based on the maxima and minima of the plotted data. If you will be interactively rotating the visualization in the figure window you should use the vis3d option.
axis([xmin xmax ymin ymax zmin zmax])
sets the limits for the
x-axis, y-axis and z-axis of the current axes.Here is the same code but with a different axes:
Z = peaks(20);
figure;
h = surf(Z);
view([-20,25]);
axis([0 30 0 30 -15 15]);
Labels¶
The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command adds a title at the top of the figure and the text function inserts text anywhere in the figure.
Here is example code that creates a simple graphics window with a default axes, a default view, a surface, and labels:
Z = peaks(20);
figure;
h = surf(Z);
view(3);
axis on;
xlabel('Longitude');
ylabel('Latitude');
zlabel('Altitude');
title('Surface of Peaks');
The Camera Toolbar
Once you have established the initial view for your visualization, you can then use the Camera toolbar to interactively control the camera. To enable the Camera toolbar, select Camera Toolbar from the figure window’s View menu. Your figure window should now look like this:
This camera toolbar contains the following parts:
See View Control with the Camera Toolbar for information on how to use the camera toolbar.
Lighting
Lighting is an effective means to enhance the visibility of surface shape and to provide a three-dimensional perspective to your visualization. MATLAB provides several commands that enable you to position light sources and adjust the characteristics of lit objects. These commands include the following:
light - Creates a light object
lighting - Selects a lighting method
material - Sets the reflectance properties of lit objects
camlight - Creates or moves a light with respect to the camera position
shading - Controls the color shading of surface and patch graphic objects
Here is example code that creates a simple graphics window with a default axes, a default view, a surface, and a camera light with phong shading:
Z = peaks(20);
figure;
h = surf(Z);
view(3);
axis on;
light;
lighting phong;
camlight('left');
shading interp;
MATLAB Data Types¶
Matrix
The fundamental data type of MATLAB is the matrix or array. A matrix is an n row by m column array of numbers or objects corresponding to numbers:
>> a = [ 1 2 3 ; 4 5 6 ; 7 8 9]
a =
1 2 3
4 5 6
7 8 9
When n is 1 the matrix is a row vector:
>> b = [1 2 3]
b =
1 2 3
When m is 1 the matrix is a column vector:
>> c = [1; 2; 3]
c =
1
2
3
and when both n and m are 1 the 1 x 1 matrix corresponds to a scalar.
>> d = [1]
d =
1
MATLAB uses graphics objects to create visual representations of data. Arrays of numbers can be used not only to store scalar and vector data but also the coordinate data of graphics objects. For example a two-dimensional array of numbers could be used to represent a surface by constructing a grid of rectangles whose vertices are defined by using the row and column indices of each element as the x- and y-coordinates and the value of each element as the z-coordinate.
Scalar volume data
single values for each point
examples: temperature, pressure, density, elevation
Vector volume data
two or three values for each point, defining the components of a vector
magnitude and direction
examples: velocity, momentum
As an example of scalar volume data, we will be using the the flow M-file (M-files are text files containing MATLAB code). The flow dataset represents the speed profile of a submerged jet within an infinite tank.
>> [x,y,z,v] = flow;
>> load wind
Modeling Visualization Algorithms¶
Modeling algorithms are often used to reveal internal details of a data set in order to discover where interesting regions exist.
[X,Y] = meshgrid(-3:0.25:3);
Z = peaks(X,Y);
figure;
mesh(X,Y,Z);
view(3);
axis([-3 3 -3 3 -10 10]);
grid on;
[X,Y] = meshgrid(-3:0.25:3);
Z = peaks(X,Y);
figure;
surf(X,Y,Z);
view(3);
axis([-3 3 -3 3 -10 10]);
grid on;
light;
lighting phong;
camlight('left');
[x,y,z,v] = flow;
figure;
xslice = 5;
yslice = 0;
zslice = 0;
slice(x,y,z,v,xslice,yslice,zslice);
view(3);
axis on;
grid on;
light;
lighting phong;
camlight('left');
shading interp;
Scalar Visualization Algorithms¶
Scalars are single data values associated with each point in the dataset. There are several different algorithms to visualize scalar data. Two common algorithms are Color Mapping and Contouring.
[x,y,z,v] = flow;
figure;
xslice = 5;
yslice = 0;
zslice = 0;
slice(x,y,z,v,xslice,yslice,zslice);
view(3);
axis([0 10 -4 4 -3 3]);
grid on;
colormap(jet(64));
colorbar('vertical');
shading interp;
If instead of mapping the lower scalar values to blues and the higher values to reds, we wish to map the lower values to reds and higher values to blues we can use the flipud function. Here is example code which shows the technique:
[x,y,z,v] = flow;
figure;
xslice = 5;
yslice = 0;
zslice = 0;
slice(x,y,z,v,xslice,yslice,zslice);
view(3);
axis([0 10 -4 4 -3 3]);
grid on;
colormap(flipud(jet(64)));
colorbar('vertical');
shading interp;
And if instead of mapping the entire scalar range of the data into the color table, we wish to set a specific range (in terms of minimum and maximum) of the data that is mapped, we can adjust the color limits. Adjusting the color limits with the caxis function enables us to emphasize a particular range of interest in the data. Here is example code which shows the result of limiting the color range from -5.0 to 2.0 so that any scalar value lower than -5.0 are mapped to the same color as -5.0 and any scalar value greater than 2.0 are mapped to the same color as 2.0:
[x,y,z,v] = flow;
figure;
xslice = 5;
yslice = 0;
zslice = 0;
slice(x,y,z,v,xslice,yslice,zslice);
view(3);
axis([0 10 -4 4 -3 3]);
grid on;
colormap(flipud(jet(64)));
caxis([-5.0,2.0]);
colorbar('vertical');
shading interp;
If you want even more control over the color mapping, you can use the colormap editor. You open the colormap editor by selecting Colormap from the Edit menu of the figure whose colormap you wish to modify.
contour(X,Y,Z,v)
draws a contour plot of matrix Z with contour
lines at the data values specified in the vector v.contour3(X,Y,Z,v)
draws a contour plot of matrix Z in a 3-D view
using X and Y to determine the x- and y-axis limits.contourslice(X,Y,Z,V,Sx,Sy,Sz,v)
draws contour plots in the x-,
y-, and z-axis aligned planes at the points in the vectors Sx, Sy, Sz.Here are some examples which shows how to generate contours for two-dimensional data:
[X,Y] = meshgrid(-3:0.25:3);
Z = peaks(X,Y);
figure;
isovalues = (-3.0:0.5:3.0);
contour(X,Y,Z,isovalues);
view(2);
axis on;
grid on;
[X,Y] = meshgrid(-3:0.25:3);
Z = peaks(X,Y);
figure;
isovalues = (-3.0:0.5:3.0);
contour3(X,Y,Z,isovalues);
view(3);
axis on;
grid on;
[x,y,z,v] = flow;
figure;
xslice = (1:3:9);
yslice = 0;
zslice = 0;
isovalues = (-3.0:0.25:3.0);
contourslice(x,y,z,v,xslice,yslice,zslice,isovalues);
view([-10 40]);
axis on;
grid on;
isosurface(X,Y,Z,V,isovalue)
computes isosurface data from the
volume data V at the isosurface value specified in isovalue. The
isosurface function connects points that have the specified value the
same way contour lines connect points of equal elevation.isosurface(X,Y,Z,V,isovalue,colors)
computes isosurface data and
also interpolates the array colors onto the scalar field and colors
the isosurface appropriately.isonormals(X,Y,Z,V,vertices)
computes the normals of the
isosurface vertices from the vertex list necessary for lighting.patch
is the low-level graphics function that creates patch
graphics objects. A patch object is one or more polygons defined by
the coordinates of its vertices.In this example we show how to create a single colored isosurface:
[x,y,z,v] = flow;
isovalue = -1;
purple = [1.0 0.5 1.0];
figure;
p = patch(isosurface(x,y,z,v,isovalue));
isonormals(x,y,z,v,p);
set(p,'FaceColor',purple,'EdgeColor','none');
view([-10 40]);
axis on;
grid on;
light;
lighting phong;
camlight('left');
In this next example we create two isosurfaces and color each of them by using the v scalar data of the flow dataset and the current colormap. The fcolors variable is a vector containing scalar values for each of the vertices in the isosurface.
[x,y,z,v] = flow;
isovalue = -1;
colors = v;
figure;
[faces,verts,fcolors] = isosurface(x,y,z,v,isovalue,colors);
p = patch('Vertices',verts,'Faces',faces,'FaceVertexCData',fcolors, ...
'FaceColor','interp','EdgeColor','none');
isonormals(x,y,z,v,p);
isovalue2 = 0;
[faces,verts,fcolors] = isosurface(x,y,z,v,isovalue2,colors);
p2 = patch('Vertices',verts,'Faces',faces,'FaceVertexCData',fcolors, ...
'FaceColor','interp','EdgeColor','none');
isonormals(x,y,z,v,p2);
view([-10 40]);
axis on;
grid on;
colormap(jet(64));
light;
lighting phong;
camlight('left');
Vector Visualization Algorithms¶
Vector data is a three-dimensional representation of direction and magnitude associated with each point in the dataset. Vector data is often used to describe rate of change of some quantity. Vectors can also be used to describe fluid flow. There are several algorithms that can be used to visualize vector data.
coneplot(X,Y,Z,U,V,W,Cx,Cy,Cz)
plots vectors as cones pointing in
the direction of the vector, having a length proportional to the
magnitude of the vector.coneplot(...,s)
automatically scales the cones to fit the graph
and then stretches them by the scale factors. If you do not specify a
value for s, a value of 1 is used. Use s = 0 to plot the cones without
automatic scaling.coneplot(...,color)
interpolates the array color onto the vector
field and then colors the cones according to the interpolated values.
The size of the color array must be the same size as the U, V, W
arrays. This option only works with cones.coneplot(...,'quiver')
draws arrows instead of cones.This example uses arrow glyphs to visualize the vector data. The arrows are scaled (proportional to the magnitude of the vectors) and are located over the entire volume.
load wind;
xmin = min(x(:));
xmax = max(x(:));
ymin = min(y(:));
ymax = max(y(:));
zmin = min(z(:));
zmax = max(z(:));
scale = 4;
figure;
[cx cy cz] = meshgrid(xmin:5:xmax,ymin:5:ymax,zmin:2:zmax);
coneplot(x,y,z,u,v,w,cx,cy,cz,scale,'quiver');
view([-35 60]);
camproj perspective;
camzoom(3.0);
axis on;
grid off;
box on;
This example uses cone glyphs to visualize the vector data. The cones are colored by wind speed.
load wind;
xmin = min(x(:));
xmax = max(x(:));
ymin = min(y(:));
ymax = max(y(:));
zmin = min(z(:));
zmax = max(z(:));
wind_speed = sqrt(u.^2 + v.^2 + w.^2);
colors = wind_speed;
scale = 4;
figure;
[cx cy cz] = meshgrid(xmin:5:xmax,ymin:5:ymax,zmin:2:zmax);
c = coneplot(x,y,z,u,v,w,cx,cy,cz,scale,colors);
set(c,'EdgeColor','none');
view([-35 60]);
camproj perspective;
camzoom(3.0);
axis on;
grid off;
box on;
light;
lighting flat;
streamline(X,Y,Z,U,V,W,startx,starty,startz)
draws stream lines
from the vector volume data.streamribbon(X,Y,Z,U,V,W,startx,starty,startz)
draws stream
ribbons from the vector volume data.streamtube(X,Y,Z,U,V,W,startx,starty,startz)
draws stream tubes
from the vector volume data.This example uses stream lines to visualize the vector data.
load wind;
xmin = min(x(:));
xmax = max(x(:));
ymin = min(y(:));
ymax = max(y(:));
zmin = min(z(:));
zmax = max(z(:));
purple = [1.0 0.5 1.0];
figure;
[sx sy sz] = meshgrid(xmin,ymin:10:ymax,zmin:2:zmax);
h = streamline(x,y,z,u,v,w,sx,sy,sz);
set(h,'LineWidth',1,'Color',purple);
view([-40 50]);
axis on;
grid off;
box on;
This example uses stream ribbons to visualize the vector data. The ribbons are colored by the magnitude of the vectors.
load wind;
xmin = min(x(:));
xmax = max(x(:));
ymin = min(y(:));
ymax = max(y(:));
zmin = min(z(:));
zmax = max(z(:));
figure;
[sx sy sz] = meshgrid(xmin,ymin:10:ymax,zmin:2:zmax)
h = streamribbon(x,y,z,u,v,w,sx,sy,sz);
set(h,'EdgeColor','none');
view([-40 50]);
axis on;
grid off;
box on;
light;
lighting flat;
camlight('left');
This example uses stream tubes to visualize the vector data. The width of the tubes are proportional to the normalized divergence of the vector field.
load wind;
xmin = min(x(:));
xmax = max(x(:));
ymin = min(y(:));
ymax = max(y(:));
zmin = min(z(:));
zmax = max(z(:));
figure;
[sx sy sz] = meshgrid(xmin,ymin:10:ymax,zmin:2:zmax);
h = streamtube(x,y,z,u,v,w,sx,sy,sz);
set(h,'EdgeColor','none');
view([-40 50]);
axis on;
grid off;
box on;
light;
lighting flat;
camlight('left');
Additional Help¶
References¶
Using MATLAB, version 7, The MathWorks, Inc.
Using MATLAB Graphics, version 7, The MathWorks, Inc.
MathWorks: MATLAB Technical Documentation and Support