4 visualization using matlab - university of …...mt1242: visualization in matlab 4 4.4 labelling...

10
MT1242: Visualization in Matlab 1 4 Visualization using matlab Matlab is very good at visualizing mathematical functions. This document provides a brief guide to what can be done in Matlab concentrating on graphing in two and three dimensions. The helpdesk provides further in-depth information about the many different plot commands in matlab. From now on we shall save all our Matlab commands in a .m file and run by pressing F5, so you won’t see the >> prompt any more. 4.1 Two dimensional plots We have already introduced the basic plot command for two dimensional vectors, however, you can change the style and feel by specifying additional information. For example, an m-file with the commands x=linspace(0,2*pi,50); y=sin(2*x); plot(x,y,’-mo’,’LineWidth’,2,... ’MarkerEdgeColor’,’k’,... ’MarkerFaceColor’,[.49 1 .63],... ’MarkerSize’,12) produces a graph of sin(2x) using a solid magenta line of width 2 point drawn with circular markers of size 12 point at the grid nodes which are coloured mint green internally and have a black edge. In the figure window the following plot is displayed 0 1 2 3 4 5 6 7 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 Note, the ’...’ allows continuation of the command onto the next line. This avoids very long lines and makes for much neater code.

Upload: others

Post on 07-Apr-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 1

4 Visualization using matlab

Matlab is very good at visualizing mathematical functions. This document provides a brief guide towhat can be done in Matlab concentrating on graphing in two and three dimensions. The helpdeskprovides further in-depth information about the many different plot commands in matlab. Fromnow on we shall save all our Matlab commands in a .m file and run by pressing F5, so you won’tsee the >> prompt any more.

4.1 Two dimensional plots

We have already introduced the basic plot command for two dimensional vectors, however, youcan change the style and feel by specifying additional information. For example, an m-file with thecommands

x=linspace(0,2*pi,50);

y=sin(2*x);

plot(x,y,’-mo’,’LineWidth’,2,...

’MarkerEdgeColor’,’k’,...

’MarkerFaceColor’,[.49 1 .63],...

’MarkerSize’,12)

produces a graph of sin(2x) using a solid magenta line of width 2 point drawn with circular markersof size 12 point at the grid nodes which are coloured mint green internally and have a black edge. Inthe figure window the following plot is displayed

0 1 2 3 4 5 6 7−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

Note, the ’...’ allows continuation of the command onto the next line. This avoids very long linesand makes for much neater code.

Page 2: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 2

In general the plot command takes the form plot(x,y,string), where string combines elementsto control the colour, marker and line style. The basic list of options involving plot are contained inthe following tables:

Abbr. Colour

b bluec Cyang Greenk Blackm Magentar Redw Whitey Yellow

Abbr. Marker

o CircleAsterisk

. Point+ Plusx Crosss Squared Diamond∧ Upward trianglev Downward triangle> Right triangle< Left trianglep Five-point starh Six-point star

Abbr. Line style

- Solid line- - Dashed line: Dotted line-. Dash-dot line

but, as we have seen, it is also possible to change the attributes of the line width and the markercolours with commands like

LineWidth width (in points) of the lineMarkerEdgeColor colour of the marker or the edge colour for filled markersMarkerFaceColor colour of the face of filled markers.MarkerSize size of the marker in points.

you can get more details on the options by searching for LineWidth in the helpdesk.

4.2 Subplots

The subplot command takes the form subplot(abc), where a is the number of rows, b is the numberof columns and c is the number of the plot. The numbering is in ascending order starting from thetop left, along each row. You can create figures with different numbers of plots in each row or column.For example a Matlab M-file with the commands

x = [1 2 3 4 5 6 7 8];

y = [2 1 6 4 8 7 3 5];

subplot(211)

plot(x,y)

subplot(223)

plot(x,y,’mo.-’)

subplot(224)

plot(x,y,’g^’,x,y,’b-’)

produces three graphs of the data points (x, y) using different line styles. The first plot stretchesover 2 columns and uses the default options, the second and third plots are both on the second rowand are labelled 3 and 4. The first of these is plotted using a magenta dot-dash line with circles atthe data points. The second is actually plotted twice; once with green triangles and then again witha blue solid line.

Page 3: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 3

1 2 3 4 5 6 7 81

2

3

4

5

6

7

8

0 2 4 6 81

2

3

4

5

6

7

8

0 2 4 6 81

2

3

4

5

6

7

8

4.3 Axes and Annotation

Various aspects of the axes of a plot can be controlled using the axis command. The axes matlabchooses for a plot are sometimes not those that we would choose ourselves, but fortunately matlabis very flexible and these can be tailored specifically to the situation at hand.

For example, the aspect ratio of a plot can be set to unity by typing axis equal. We can removethe axes altogether using axis off or we could make limit the axes to the range of the data usingaxis tight.

2 4 6 81

2

3

4

5

6

7

8

axis tightaxis off

0 2 4 6 80

2

4

6

8Standard

2 4 6 81

2

3

4

5

6

7

8axis equal

You can manually specify the range of the axes for x and y by using axis([xmin xmax ymin ymax]).Finally if you decide that matlab’s choice was the best after all, you can revert to the default bytyping axis auto.

Page 4: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 4

4.4 Labelling

You may have noticed in the previous figure that all of the plots had some form of labelling. Thereare four main ways of labelling a plot or subplot. Often the easiest way is by using the commands

title Graph titlexlabel x-axis (horizontal)ylabel y-axis (vertical)

in the M-file. But if you need to make special one off labels to highlight certain features on the graphyou can use the toolbar in the figure window and the mouse to add text and arrows to your plot.For example the M-file produces most of the following output and then the mouse has been used toadd some further text and arrows

alpha=0.01;

x=linspace(1900,2000);

y=exp(alpha*x);

plot(x,y)

title(’increase in population over the last hundred years’)

xlabel(’years’)

ylabel(’population’)

1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 20001.5

2

2.5

3

3.5

4

4.5

5x 10

8 increase in population over the last hundred years

years

popu

latio

n

This shows exponential growth

But don’t quote me on the numbers!

4.5 Multiple plots on the same graph and legends

We often want to plot multiple graphs on the same plot and distinguish between the curves. Theeasiest way to do this is draw the lines using different line styles with the plot command and theninclude a legend to tell the reader what each of the graphs is. matlab will place a box in aspecified location on the graph in order to explain the different line styles. The command is simplylegend(‘string1’,‘string2’,...,‘stringn’), where each string is the description associatedwith each line style.

For example, we may a series of truncated Taylor approximations to ln(x) at x = 1 and comparethem to the graph of ln(x) with the following code

Page 5: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 5

x=0.5:.01:2.5;

p1=log(x);

p2=log(1)+(x-1);

p3=(x-1)-((x-1).^2)./2;

p4=(x-1)-((x-1).^2)./2+2*((x-1).^3)./6;

plot(x,p1,’k-’,x,p2,’k--’,x,p3,’k-.’,x,p4,’k:’)

legend(’ln(x)’,’n=1’,’n=2’,’n=3’)

title(’Taylor approximation of ln(x) near x=1’,’Fontsize’,14)

Note that multiple graphs are achieved by a single plot command. An alternative method is to plotindividual graphs and use the command hold on before the first image to stop Matlab clearing theplot window before the next plot is drawn. This feature is turned off by the command hold off

0.5 1 1.5 2 2.5−1

−0.5

0

0.5

1

1.5Taylor approximation of ln(x) near x=1

ln(x)n=1 n=2 n=3

4.6 Plotting symbolic expressions in two dimensions

Notice that in the previous figure, we had to explicitly specify the range of values for the vector x inorder to produce other vectors containing the polynomial approximations we were considering. Thereis a more straightforward technique than this using matlab faciliities for the plotting of symbolicfunctions.

As before, we must start by specifying to matlab which variables we would like it to consider assymbolic. The command ezplot can then be used plot either parametrically or implicitly definedcurves in two dimensions. We plot both (x, y) = (cos t, sin t) and x2 + y2 = 1. The commands to dothis can again be stored in an M-file

clear

syms x y t s theta

subplot(121)

ezplot(cos(t),sin(t),[0, 2*pi])

subplot(122)

ezplot(x^2 + y^2 - 1, [-1, 1, -1, 1])

Page 6: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 6

−0.5 0 0.5 1

−1.5

−1

−0.5

0

0.5

1

1.5

x

y

x = cos(t), y = sin(t)

−1 −0.5 0 0.5 1−1

−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

x

y

x2+y2−1 = 0

This approach has the advantage of being able to type the mathematics in in standard notation,i.e. without the element-wise operations, but there is less flexibility for altering the line style etcthan with the plot command.A summary of the main two-dimensional plotting commands is given in the following table:

plot Simple x-y plotloglog Plot with logarithmically scaled axessemilogx/semilogy Plot with logarithmically scaled x or y-axisezplot/ezpolar Plotting symbolically defined functionspolar Polar co-ordinate plotfplot Autmoatic function plot; similar to ezplot

bar/barh Bar chart of given data or horizontal versionhist Histogram of given datapie Pie chart of given dataquiver Plots a vector field using arrows (see Chapter 4)

4.7 Three dimensional plots

The function plot3 is the same as the plot function, but in three dimensions. In addition to thisstandard three dimensional plot, we can also create surfaces and contour plots. To do this you needto set up a grid in the x and y directions with linspace and then create a two-dimensional grid ofcoordinate [X,Y ] with meshgrid before you can define the function and plot a surface with surf

x=linspace(-5,5);

y=linspace(-5,5);

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

Z=Y./(1+X.^2+Y.^2);

surf(X,Y,Z)

Page 7: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 7

−5

0

5

−5

0

5

−0.5

−0.4

−0.3

−0.2

−0.1

0

0.1

0.2

0.3

0.4

0.5

This is where Matlab becomes very powerful. In the figure window you can select View andthen from the Camera toolbar or drop down menu you can choose orbit camera. This allows youto rotate the plot in 3-space and even set it spinning, so that you can perceive the 3D nature of thesurface.

In what ever field of work you enter three-dimensional plots are often required to represent dataor functions and it is common practice to use contour plots. You can think of these like topographicmaps of mountains where the contours represent lines of equal height. Matlab will draw these foryou. For example replacing surf(X,Y,Z); shading interp; with contourf(X,Y,Z) produces afilled contour map

x=linspace(-5,5);

y=linspace(-5,5);

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

Z=Y./(1+X.^2+Y.^2);

contourf(X,Y,Z)

−5 −4 −3 −2 −1 0 1 2 3 4 5−5

−4

−3

−2

−1

0

1

2

3

4

5

To help you understand the relationship between surface plots and the contours it is sometimeshelpful to replace the command surf with surfc to see the contours and the surface on the sameplot, e.g.

Page 8: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 8

−5

0

5

−5

0

5

−0.5

−0.4

−0.3

−0.2

−0.1

0

0.1

0.2

0.3

0.4

A summary of the main three dimensional plotting commands is given in the following table; notemany of them are similar to the two dimensional commands we considered earlier:

plot3 Simple x-y-z plotcontour Contour plotcontourf Filled contour plotcontour3 3D contour plotmesh Wireframe surface plotmeshc Wireframe surface plot plus contoursmeshz Wireframe surface plot with curtainsurf Solid surface plotsurfc Solid surface plot plus contourswaterfall Unidirectional wireframe plotbar3 3D bar graphbar3h 3D horizontal bar graphpie3 3D pie chartfill3 Polygon fillcomet3 3D animated, comet-like plotscatter3 3D scatter plotstem3 Stem plot

You can use the commands title, xlabel, ylabel and zlabel to add captions and labels to thecoordinate axes.

4.8 Plotting symbolic functions in three dimensions

matlab also has a number of commands for plotting symbolic expressions. Specifically the com-mands we consider are ezplot for curves in 2D, ezpolar for plotting in polar coordinates, ezplot3for curves in 3D, ezsurf for 3D surfaces and ezcontour for contour plots.

Page 9: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 9

To begin with we must again notify matlab of the variables which we would like it to consider assymbolic. Then you can define the function and plot it using ezplot3 to plot parametric curves in3D

clear

syms x y t s theta

ezplot3(t*cos(t),t*sin(t),t,[0 50])

−50

0

50

−50

0

500

10

20

30

40

50

x

x = t cos(t), y = t sin(t), z = t

y

z

The function is somewhat easier to enter as we don’t have to use element-wise operations or themeshgrid function to generate the values, however, we have less control on the output. Once againthe View-Camera menu can be used to move the plot around, rotate it and spin it to help visualizethe curve from different angles.

4.9 Symbolic Surfaces in 3D

ezsurf is for plotting surfaces, either parametrically defined or giving the z-coordinate in terms ofx and y. We plot the two surfaces (x, y, z) = (s cos t, s sin t, s) and z = x + y + 4 using the hold

command to stop Matlab clearing the window

clear

syms s t x y

hold on

ezsurf(x+y+4)

ezsurf(s*cos(t),s*sin(t),s);

hold off

after using the camera toolbar we can rotate the plot to see the intersection of the two surfaces

Page 10: 4 Visualization using matlab - University of …...MT1242: Visualization in Matlab 4 4.4 Labelling You may have noticed in the previous figure that all of the plots had some form

MT1242: Visualization in Matlab 10

−8−6−4−202468

−8

−6

−4

−2

0

2

4

6

8

−8

−6

−4

−2

0

2

4

6

8

x = s cos(t), y = s sin(t), z = s

x

y

z

ezsurfc is the same as ezsurf but adds a contour plot of the function below the surface. Forinstance, we can use the symbolic method to draw the function f = y/(1 + x2 + y2), which we drewby a direct method earlier

clear

syms x y f

f=y/(1+x^2+y^2);

ezsurfc(f);

−5

0

5

−6−4−20246

−0.5

−0.4

−0.3

−0.2

−0.1

0

0.1

0.2

0.3

0.4

0.5

x

y/(1+x2+y2)

y