Section 3 Data Visualization - College of...
Transcript of Section 3 Data Visualization - College of...
MAE 4020/5020 – Numerical Methods with MATLAB
SECTION 3: DATA VISUALIZATION
2
Data Visualization
K. Webb MAE 4020/5020
In this section of notes we’ll look at several different ways to plot data 2‐D plots – plotting data that is a function of a single variable – by far the most common type of plot
3‐D plots – for data that is a function of two variables –e.g. a function of position in a plane, vector fields, etc.
Animation – can be very useful for demonstration and presentation purposes
2‐D Plotting3
K. Webb MAE 4020/5020
4
Basic 2‐D Plotting – plot(…)
K. Webb MAE 4020/5020
5
Basic 2‐D Plotting – plot(…)
K. Webb MAE 4020/5020
Syntax:plot(x,y,’LineSpec’,’PropName’,PropValue)
x and y are equal‐length vectors of data x data is the abscissa – plotted on the horizontal axis y data is the ordinate – plotted on the vertical axis
LineSpec defines the type and color of the line used to plot and the shape of the marker placed at each data point – (optional)
PropNamemay be any number of properties, such as the width of the line, and is followed by its value –(optional) Multiple property/value pairs may be specified in succession
6
LineSpec – Line Style
K. Webb MAE 4020/5020
plot(x,y,’LineSpec’,’PropName’,PropValue)
Three components – line style,marker, color Specify some or all
Line Style specifiers:
Default is a solid line
Specifier Line Style
'-' Solid
'--' Dashed
':' Dotted
'-.' Dash‐dot
7
LineSpec – Marker
K. Webb MAE 4020/5020
Marker specifiers:
Default is no marker Markers are placed at every data point – can get crowded for closely spaced data
Specifier Marker'+' Plus sign'o' Circle'*' Asterisk'.' Point'x' Cross's' Square'd' Diamond
Specifier Marker'^' Upward‐
pointing triangle'v' Downward‐
pointing triangle'>' Right‐pointing
triangle'<' Left‐pointing
triangle'p' pentagram'h' hexagram
8
LineSpec – Line/Marker Color
K. Webb MAE 4020/5020
Color specifiers:
Default color is blue If multiple x,y pairs are specified in a single plot command, line/marker colors will cycle through automatically (white is skipped for white background)
Specifier Color'r' Red'g' Green'b' Blue'c' Cyan
Specifier Color'm' Magenta'y' Yellow'k' Black'w' White
9
Line Properties
K. Webb MAE 4020/5020
plot(x,y,’LineSpec’,’PropName’,PropValue)
Property name and value specified in pairsLineWidth— numeric value (points) – 2 is good for most plots
MarkerEdgeColor—color of the marker or edge color for filled markers
MarkerFaceColor—face color of filled markersMarkerSize— numeric value (points)
10
Using plot(…)
K. Webb MAE 4020/5020
figure(n)• Creates figure window• Brings window to front if already created
clf• Clears figure window
grid on• Turns on grid lines
hold on• Superimpose multiple traces• Plot command won’t erase existing traces
11
Plot Annotation
K. Webb MAE 4020/5020
Title
title(‘string’,‘PropName’,‘PropValue’)
Axis labels
xlabel (‘string’…)
ylabel (‘string’…)
Text
text(x,y,‘string’…)
Text string printed at location (x,y) on the current figure axes Special characters
MostMATLAB annotation functions can interpret TeX character sequences E.g. \beta, \mu, \it, \div, etc. Search help for ‘Text Properties’ for a table of TeX characters
12
Plot Annotation
K. Webb MAE 4020/5020
White background – good for printing over gridlines
13
Plot Legend
K. Webb MAE 4020/5020
Add a legend to a figure to identify multiple traceslegend(‘string_1’,‘string_2’,…,‘string_n’…
‘Location’,‘location’)
Strings assigned to curves in the order they were plotted
location is specified using cardinal points E.g. ‘NorthEast’, ‘West’, etc.MATLAB can also choose the location with the least interference with traces:legend(……’Location’,‘Best’)
14
Plot Legend
K. Webb MAE 4020/5020
Note the use of an ellipsis (…) to allow for breaking a single command over multiple lines
15
Axis Scaling
K. Webb MAE 4020/5020
Specify the range of all axes at once
axis([xmin,xmax,ymin,ymax])
Or, specify x and y axes individually
xlim([xmin,xmax])
ylim([ymin,ymax])
Use ±inf to allow for autoscaling, e.g.:
axis([-inf,1e4,0,40])
16
Axis Scaling
K. Webb MAE 4020/5020
17
Subplots
K. Webb MAE 4020/5020
Plot multiple sets of axes on a single figure
subplot(m,n,p) Figure window divided into m rows and n columns p is the current subplot index
Counted from left to right, top to bottom subplot command activates the pth subplot
All subsequent plotting/annotation commands issued to the active subplot
To plot to another subplot, issue subplot with a new value for p
18
Subplot Numbering
K. Webb MAE 4020/5020
subplot(m,n,p)
m and n can vary within a figure window
p can be specified as a range using the colon operator
19
Including Variable Values in Annotation
K. Webb MAE 4020/5020
Often, we want to include a variable value in a title or text annotation
A couple of options: sprintf(…) – does not recognize TeX character sequences – no special characters or Greek letters
num2str(…) – recognizes TeX characters – very often important for annotations
20
Annotations Using num2str(…)
K. Webb MAE 4020/5020
num2str(A,’FormatSpec’)
Converts the value of the variable A to a string according to FormatSpec
FormatSpec specifies Type of number (e.g. fixed‐point, integer, etc.) Field width and precision
The string created from the variable value can then be placed in a string array that is passed to the annotation function
21
Annotations Using num2str(…)
K. Webb MAE 4020/5020
num2str(…) used to generate one element – the value of – of the string array passed to the title function
22
Controlling Axis Tick Marks – XTickLabel
K. Webb MAE 4020/5020
gca – get current axes Returns a handle to the currently active axes
Cell array enclosed in curly brackets, {…}
TickLabel commands do not interpret TeX characters
23
Controlling Axis Tick Marks – YTick
K. Webb MAE 4020/5020
Non‐uniform Tickspacing is allowed
If TickLabel is not specified, default (numeric) labels are placed at each tick mark
24
Dual y‐Axes – plotyy(…)
K. Webb MAE 4020/5020
Generate plot with different y‐axes on right and left sides of figure
[AX,H1,H2] = plotyy(x1,y1,x2,y2)
AX(1): handle to the left y‐axisAX(2) : handle to the right y‐axisH1: handle to the plot assigned to the left y‐axisH2: handle to the plot assigned to the right y‐axis
Use the axis handles to specify axis properties YTick, YTickLabel, ylabel, etc.
Use the plot handles to specify plot properties LineStyle, Color, etc.
25
Dual y‐Axes – plotyy(…)
K. Webb MAE 4020/5020
Use set(…) to modify plot properties Pass the handle to the object to be modified
26
Logarithmic Axes
K. Webb MAE 4020/5020
Useful for displaying datasets that span a very large range Log‐log plot – both axes are logarithmic
loglog(x,y,‘LineSpec’,…)
Logarithmic X‐axis
semilogx(x,y,‘LineSpec’,…)
Logarithmic Y‐axis
semilogy(x,y,‘LineSpec’,…)
Generating ind. variable vector for log‐x plots:
logspace(X1,X2,N)
27
Logarithmic Axes
K. Webb MAE 4020/5020
28
Strip Plot – strips(…)
K. Webb MAE 4020/5020
strips(y,SD,fs,…) y: data vector to plot
SD: time duration of each strip
fs: sample rate
29
Stem Plot – stem(…)
K. Webb MAE 4020/5020
Good for plotting discrete‐time data E.g. digital control, signal processing applications
stem(x,y,…)
30
Plotting Zero‐Order‐Hold Data – stairs(…)
K. Webb MAE 4020/5020
Again, useful for discrete‐time applications E.g. digital controls
stairs(x,y,…)
31
Plotting Vector Fields – quiver(…)
K. Webb MAE 4020/5020
x,y: matrices of x,ycoordinates –generate with meshgrid(…) –more later
u,v: velocity components at x,ylocations – matrices
quiver(x,y,u,v)
32
Streamline Plots – streamline(…)
K. Webb MAE 4020/5020
x,y,u,v: same as for quiver(…)
xs,ys: starting coordinates for streamlines
streamline(x,y,u,v,xs,ys)
3‐D Plots33
K. Webb MAE 4020/5020
34
3‐D plots
K. Webb MAE 4020/5020
We’ll consider two main categories of 3‐D plots: 3‐D line plots
A single independent variable – two of the variables are functions of the third
A line in 3‐D space
Surface plots A function of two variables – two independent variables, on dependent variable
Height of the function is dependent on position in the x,y plane
35
3‐D Line Plot – plot3(…)
K. Webb MAE 4020/5020
One independent variable, two dependent variables E.g. 3‐D line plot – a curve in three‐dimensional space
plot3(x,y,z,’LineSpec’,’PropName’,PropValue,…)
x, y, and z inputs are vectors One x and one y value for each z value
36
3‐D Line Plot – plot3(…)
K. Webb MAE 4020/5020
37
3‐D Surface Plots
K. Webb MAE 4020/5020
Functions of two variables can be plotted as surfaces in 3‐D space
Functions of one variable get evaluated at each point in the input variable vector
Say we want to evaluate a function, , over a range of and values, e.g. and
Must evaluate not only at each point in and , but at all possible combinations of and
38
3‐D Surface Plots ‐ Input Matrices
K. Webb MAE 4020/5020
Must evaluate at every point in the specified region of the x‐y plane 20 points – 20 x‐values, 20 y‐values
1 2 3 41 2 3 41 2 3 41 2 3 41 2 3 4
1 1 1 12 2 2 23 3 3 34 4 4 45 5 5 5
39
3‐D Surface Plots – meshgrid(…)
K. Webb MAE 4020/5020
[Xm,Ym] = meshgrid(x,y)
x and y are vectors Define ranges of x and y in the x‐y plane
Xm and Ym are matrices All coordinates in the region of the x‐y plane specified by vectors x and y
size(Xm)=size(Ym)=(length(y),length(x))
Rows of Xm are x Columns of Ym are y
40
Function of Two Variables – Input Matrices
K. Webb MAE 4020/5020
The inputs to are matrices Create from x and y vectors using meshgrid(…)
Example: Evaluate for 2 2, 2 2
41
Surface Plot – surf(…)
K. Webb MAE 4020/5020
surf(x,y,z)
Use view(azim,elev)to set viewing angle of 3‐D plots
42
Surface Plot with Contours – surfc(…)
K. Webb MAE 4020/5020
Same surface as surf(…)
Also draws a contour plot in the x‐y plane
surfc(x,y,z)
43
Mesh Plot – mesh(…)
K. Webb MAE 4020/5020
like surf(…) but only wireframe is plotted
mesh(x,y,z)
44
Mesh Plot with Contours – meshc(…)
K. Webb MAE 4020/5020
Same wireframe as mesh(…)
Also draws a contour plot in the x‐y plane
meshc(x,y,z)
45
2‐D Contour Plot – contour(…)
K. Webb MAE 4020/5020
A 2‐D contour plot of the surface defined by z
N contours drawn
contour(x,y,z,N)
46
3‐D Contour Plot – contour3(…)
K. Webb MAE 4020/5020
A 3‐D contour plot of the surface defined by z
N contours drawn at their corresponding zvalues
contour3(x,y,z,N)
47
Waterfall Plot – waterfall(…)
K. Webb MAE 4020/5020
Use z’ for column‐oriented data
Useful for parameterized responses, spectrograms, etc.
waterfall(x,y,z)
48
Animation – Creating Movies
K. Webb MAE 4020/5020
To create a movie, generate frames one‐at‐a‐time and write successively to a video file
Create and open a VideoWriterObject – where the video is written
vidfile=VideoWriter(‘filename’,‘profile’)
open(vidfile)
Plot frames in a loop, grabbing each plot as a single frame
frame=getframe(H)
H is a handle to a figure or axes
Write each frame to vidfile
writeVideo(vidfile,frame)
Movie stored in pwd in filename.avi by default – can specify format
49
Animation – Setting Video Properties
K. Webb MAE 4020/5020
vidfile=VideoWriter(‘filename’,‘profile’)
vidfile is a structure – can edit some of its fields to control video properties
Frame rate – for a frame interval of dt:
vidfile.FrameRate=1/dt;
Quality – 0…100 – higher value, higher quality, larger file size –(default: 75):
vidfile.Quality=90;
profile – specifies the type of video encoding E.g. ‘Archival’, ‘Motion JPEG AVI’(default), ‘MPEG-4’, etc.
50
Animation – Example
K. Webb MAE 4020/5020
Animate the motion of a projectile through the earth’s gravitational field, neglecting drag Initial velocity: Launch angle:
Gravitational acceleration: .
Horizontal position:
Vertical position:
51
Animation – Example
K. Webb MAE 4020/5020
Calculate trajectory Create and open the video file, specifying frame rate and quality
Get figure handle when creating figure
Loop, creating the video frame‐by‐frame
Grab each frame and write it to vidfile
Close vidfile
52
Animation – Example
K. Webb MAE 4020/5020
53Exercise
Create a surface plot of:
,sin
Plot over the range of
10 1010 10
Choose step size of and to produce a good‐looking plot Try different types of surfaces, with and without contours Choose the best viewing angles and set those in your code If is evaluated at , 0,0 , the result is NaN
A hole in the surface results How can you either avoid this or correct for it (i.e., set
0,0 1)?
Exercise – Create a Surface Plot
K. Webb MAE 4020/5020