CS 211 Lesson 16
Introduction to Plotting
Quote:
Hold yourself responsible for a higher standard than anybody else expects of you. Never excuse yourself. Henry Ward Beecher
Lesson Objectives:
To understand the various types of graphs and charts that are commonly created
Be able to create basic 2-dimensional plots
Be able to annotate 2-D plots with a title, labels, legends, and grid lines
Know the different options for plot line styles, markers, and legends
Be able to adjust the limits of a plot's axes
Be able to display multiple graphs in the same axes
Be able to display multiple axes in the same graphics window using subplots
Know the options for plotting with logarithmic scales
Be able to incorporate a MATLAB plot into other documents (e.g., Microsoft Word)
Lesson:
I. MATLAB Concepts
A. Plotting overview
MATLAB has an extensive set of plotting functions. We will only present an overview of MATLAB's capabilities. If you are interested in learning all of the possible plotting features in MATLAB, search for "Specialized Plotting" in MATLAB's help system.
We will cover two major topics in the next two lessons on plotting:
How to create a plot from a set of data.
How to set the attributes of a plot to get the appearance you desire.
Graphs vs. Charts
- A graph is a visual display of the relationship between two or more variables. Each variable is associated with an axis of the graph and the values vary continuously over a range of values. Common types of graphs are line graphs, scatter plots, and histograms.
- A chart is a visual display of data where the horizontal (x) axis does not represent a continuous variable, but rather a set of discrete (non-continuous) values (e.g., USAFA academic departments: DFCS, DFEE, DFAS, etc.). Common types of charts are bar charts and pie charts.
- MATLAB does not make distinctions between graphs and charts -- BUT you should make the distinction and use an appropriate plotting function to accurately represent your data.
- How can you choose an appropriate plot type for a given problem? Ask yourself the following questions and choose accordingly (recognizing that there are always exceptions to these general guidelines).
Questions? If true, create a -- Is time one of my data values? Create a line plot.
(typically the x-axis represents time)Do I want to compare the relationship between two independent variables, apart from time? Create a scatter plot. Is one of my data variables discrete (not continuous over a range)? Create a bar chart. Am I plotting frequencies or distributions (i.e., how many times certain values occur within a data set)? Create a histogram. Am I plotting percentages? Create a pie chart.
MATLAB functions for generating plots (a subset)
Plot type 2D Plots 3D Plots line graphs plot(), ezplot(), fplot()
semilogz(), semilogy(), loglog()plot3(), ezplot3() scatter plots (graph) scatter() scatter3() histograms (graph) hist(), histc() bar charts bar(), barh() bar3(), bar3h() pie charts pie() pie3() surface plots (graph) surf() mesh plots (graph) mesh() contour plots (graph) contour() contour3() B. Line graphs using plot()
The plot(Xvalues,Yvalues) function is one way to create a line graph, where the two arguments are row vectors, both of the same size, that represent the (x,y) values to be plotted.
Plotting the function y = f(x) is typically a 3-step process:
Steps Example
- Define a row vector of domain values.
- Create a row vector of the corresponding range values.
- Use the plot() function to graph the data points
x = -2*pi:0.1:2*pi;
y = sin(x);
plot(x,y)
plot() draws a straight line between each adjacent point defined by the row vectors, i.e.,(x(1), y(1)), (x(2), y(2)), ... (x(end), y(end)). If your plot does not produce a smooth curve, add more points to your vector of x values. For example:
x = -2*pi:1:2*pi;
y = sin(x);
plot(x,y)x = -2*pi:0.1:2*pi;
y = sin(x);
plot(x,y)
plot() draws into a "figure window." If no figure window is currently open, plot will create a new figure window to draw into. If a figure window is already open, plot() will replace the contents of the open figure window. Use the close() function to close a figure window.
Multiple lines can be drawn onto a single graph (technically called an axes) in two ways:
- Include more than one pair of row vectors in a single call to plot(). For example:
- Use the hold('on') function call to keep subsequent plot commands drawing into the same axis (without replacing the existing graph). For example:
x = -2*pi:0.1:2*pi;
plot(x, sin(x), x, cos(x));x = -2*pi:0.1:2*pi;
plot(x, sin(x))
hold('on');
plot(x, cos(x));
A plot can be annotated in many ways. Some of the possible annotations are:
Annotation Examples Add a title title('x * sin(x)') Label the x axis xlabel('x'); Label the y axis ylabel('y'); Add a grid background grid('on'); Write text on the graph.
(The x, y location is specified in axes coordinates.)text(x, y, 'text');
text(0, pi, 'curve 1');Add a legend
(to label multiple plot lines)legend('sin(x)', 'cos(x)', 'tan(x)');
legend('sin(x)', 'cos(x)', 'Location', 'NorthEastOutside');
Valid locations include:
North, South, East, West,
NorthEast, NorthWest, SouthEast, SouthWest,
NorthOutside, SouthOutside, EastOutside, WestOutside, NorthEastOutside, NorthWestOutside, SouthEastOutside, SouthWestOutside,
Best, BestOutside- A plot line's "style" can be modified with a linespec string. A linespec string contains three code values that represent "line style", "marker symbol", and color (in that order). The allowable codes for each value are shown below:
Line Style Marker Symbol Color
- Solid line (default) -- Dashed line : Dotted line -. Dash-dot line
+ Plus sign o Circle * Asterisk . Point x Cross s Square d Diamond ^ Upward triangle v Downward triangle > Right triangle < Left triangle p pentagram h hexagram (star)
r Red g Green b Blue c Cyan m Magenta y Yellow k Black w White If you want each plot line to be unique, a linespec string should be passed to the plot() function for each pair of vectors. Your linespec string does not have to contain a code for all three attributes: "line style", "marker symbol", and color. If you leave one or more values out of the linespec string, the corresponding default value is used.
x = -2*pi:0.1:2*pi;
plot(x, sin(x), ':or', ...
x, cos(x), '--xb');x = -2*pi:0.1:2*pi;
plot(x, sin(x), ...
x, cos(x), '-sg');
The length of the x and y axes is automatically set based on the minimum and maximum values in the x and y vectors graphed by plot(). You can manipulate the limits on each axis using the axis() function.
With no arguments, axis() returns a vector with the current plot's axes limits, in the order [xmin xmax, ymin, ymax].
Plot_limits = axis()
With a vector of four values as an argument, axis() sets the x and y limits of the current plot
axis([xmin xmax ymin ymax])
C. Line graphs using fplot ()
The fplot(string, vector) function plots a function supplied as a character string over a given domain.
Using fplot eliminates the need to generate a vector of domain (x) values.
The fplot function is adaptive - it adds more points where the function is changing rapidly to generate a smooth curve.
Example 1 Example 2 fplot('x.^2', [-10 10]);
fplot('sin(x)/x', [-4*pi 4*pi]); D. Line graphs with non-linear scales
Logarithmic scales (e.g., 1, 10, 100, 1000, ...) are useful for graphing functions that quickly generate large values along an axis.
The semilogx() function plots x data on a logarithmic axis and y data on a linear axis
The semilogy() function plots x data on a linear axis and y data on a logarithmic axis
The loglog() function plots x and y data on logarithmic axes
These three non-linear plot functions have the same usage and attributes as the plot() function that was described previously.
E. Subplots - multiple plots in a single figure window
The subplot() function allows you to create multiple axes in a single figure window.
subplot(r, c, p) creates a figure window with r rows and c columns of axes and creates an axes at position p, where p is the row-major index for the r x c positions in the figure. For example:
Create a figure with 2 axes, one above the other Create a figure with 4 axes in a 2x2 grid x = -2*pi:0.1:2*pi;
subplot(2,1,1)
plot(x, sin(x)); xlabel('sin(x)');
subplot(2,1,2)
plot(x, cos(x)); xlabel('cos(x)');x = -2*pi:0.1:2*pi;
subplot(2,2,1)
plot(x, sin(x)); xlabel('sin(x)');
subplot(2,2,2);
plot(x, cos(x)); xlabel('cos(x)');
subplot(2,2,3);
plot(x, tan(x)); xlabel('tan(x)');
subplot(2,2,4);
plot(x, sinh(x)); xlabel('sinh(x)');
F. Saving graphics
Operation Syntax Examples Print graph to a printer Save graph to a file print -dformat filename
print -djpeg myplot.jpg
print -dbmp myplot.bmp
print -dtiff myplot.tif
Copy graph to the clipboard keyboard shortcut - ALT-PRINT_SCREEN
G. Formatting special symbols in text strings
When specifying a string of text to display (e.g., a label, title, text), you can change the font, font size, font style, and font spacing using stream modifier character sequences as follows:
stream modifier Explanation \bf
changes subsequent text to bold face \it changes subsequent text to italic face \rm changes subsequent text to the normal default font \fontname{fontname} Specify the name of the font family to use \fontsize{fontsize} Specify the font size in FontUnits _{ } makes text inside braces subscript ^{ } makes text inside braces superscript
- You can include special math and Greek symbols using special character sequences. (Search for "text properties" in the MATLAB help system to find a list of all possible character sequences.
II. Good Programming Practices
If possible, only calculate values once.
For example, DON'T do this:
plot(-2*pi:0.1:2*pi, sin(-2*pi:0.1:2*pi),
-2*pi:0.1:2*pi, cos(-2*pi:0.1:2*pi));
Instead, DO this:
x = -2*pi:0.1:2*pi;
plot(x, sin(x), x, cos(x));
III. Algorithms
(None for this lesson)
Lab Work: Lab 16
References:
Chapman Textbook: sections 2.11, 3.5
MATLAB reference page "Specialized Plotting"
MATLAB reference page "text properties"