Chapter 6
IN THIS CHAPTER
Defining and understanding plots
Working with the plot function
Changing plot specifics
Creating 2D plots
MATLAB includes fabulous routines for plotting (or graphing) the data and expressions that you supply to the software. Using MATLAB’s familiar interface, you can produce visual representations of various functions and data sets, including 2D x-y graphs, log scales, bar, and polar plots, as well as many other options. The visuals that MATLAB produces resemble anything from the graph of an algebraic equation to pie charts often used in business and to specialized graphs.
In this chapter, you find out how to use 2D plotting functions to create expression and data plots and how the same process works with other plotting routines in MATLAB. You also discover the commonly used visual styles for representing various types of data, how to combine plots, and how to modify the plots to match specific data sets.
Considering Plots
A plot is simply a visualization of data. Most people see a series of numbers in a table and can’t really understand its meaning. Interpreting what the data means is hard to do without thinking about the relationship between data points. A plot makes the relationships between data points more obvious to the viewer and helps the viewer see patterns in the data. The following sections help you discover how MATLAB plots are special and can make the visualization of your data interesting and useful.
Understanding what you can do with plots
People are visually oriented. You could create a standard table showing the data points for a sine wave and have no one really understand that it was a sine wave at all or that the data points move in a certain way. However, if you plot that information, it becomes apparent to everyone that a sine wave has a particular presentation and appearance. The pattern of the sine wave becomes visible and understandable.
A sine wave consists of a particularly well-known set of data points, so some people might recognize the data for what it is. As your data becomes more complex, however, recognizing the patterns becomes more difficult — to the point at which most people won’t understand what they’re seeing. So the first goal of a plot is to make the pattern of data readily apparent.
Presentation is another aspect of plotting. You can take the same data and provide multiple views of it to make specific points — the company hasn’t lost much money on bad widgets, for example, or the company has gained quite a few new customers due to some interesting research. Creating the right plot for your data defines a specific view of the data: It helps you make your point about whatever the data is supposed to represent.
Creative interaction with the data is another reason to use plots. People see not only the patterns that are present in plots but also see the ones that could be present given the right change in conditions. It’s the creative interaction that makes plotting data essential for scientists and engineers. The ability to see beyond the data is an important part of the plotting process.
Comparing MATLAB plots to spreadsheet graphs
Although it might seem obvious at first, spreadsheet graphs are generally designed for use in business. As a result, the tools you find are better suited to making a point about some business need, such as this quarter’s sales or the project production rate in the factory. A spreadsheet graph includes the tools of business, such as the need to add trend lines of various sorts to show how the numbers are changing over time.
MATLAB plots are more suited to scientific and engineering needs. A MATLAB plot does include some of the same features as a spreadsheet graph. For example, you can create a pie chart in either environment and assign data points to the chart in about the same manner. However, MATLAB includes plots that you can’t find in the business environment, such as a semilogx (used to plot logarithmic data; see https://www.mathworks.com/help/matlab/ref/semilogx.html). A business user probably wouldn’t have much need for a stem plot — the plot that shows the frequency at which certain values appear.
The way in which the two environments present information differs as well. A spreadsheet graph is designed to present an overview in an aesthetically pleasing manner. The idea is to convince a viewer of the validity of the data by showing general trends. Business users tend not to have time to dig into the details; they need to make decisions quickly based on trends. MATLAB graphs are all about the details. With this in mind, you can zoom in on a graph, examine individual data points, and work the plot in ways that a business user doesn’t require.
No best approach to presenting information in graphic form exists. The only thing that matters is displaying the information in a manner that most helps the viewer. The essential difference in the two environments is that one allows the viewer to make decisions quickly and the other allows the viewer to make decisions accurately. Each environment serves its particular user’s needs.
Creating a plot using commands
MATLAB makes creating a plot easy. Of course, before you can create any plot, you need a source of data to plot. The following steps help you create a data source and then use that data source to generate a plot. Even though MATLAB’s plotting procedure looks like a really simplistic approach, it’s actually quite useful for any data you want to plot quickly. In addition, it demonstrates that you don’t even have to open any of the plotting tools to generate a plot in MATLAB.
1. Type x = -pi:0.01:pi; and press Enter in the Command Window.
MATLAB generates a vector, x, and fills it with a range of data points for you. The data points begin at –pi and end at pi, using 0.01 steps. The use of the semicolon prevents the output of the data points to the Command Window, but if you look in the Workspace window, you see that the vector has 629 data points.
2. Type plot(x, sin(x)), grid on and press Enter.
The plot shown in Figure 6-1 appears. It’s a sine wave created by MATLAB using the input you provided.
FIGURE 6-1: The plot uses all the defaults that MATLAB provides, except for turning the grid on.
The plot() function accepts the data point entries that you provide. The vector x contains a series of values between –pi and pi. Taking the sine of each of these values using the sin() function creates the values needed to generate the plot shown. This version of the plot() function shows the minimum information that you can provide. The x value that appears first contains the information for the x-axis of the plot. The sin(x) entry that appears second contains the information for the y-axis of the plot.
The addition of the grid on command displays a grid on the plot to make it easier to see line values. Normally, MATLAB displays a plot without a grid to keep from hiding values from view or potentially causing misinterpretations. You can add a graphing command, like grid on, by adding to the same line as plot() with a comma separation.
You can create any sort of plot using commands, just you can use the graphic aids (such as the GUI shown in Figure 6-1) that MATLAB provides. For example, type area(x,sin(x)), grid and press Enter. You see the plot shown in Figure 6-2. However, this time the sine wave is shown as an area plot. MATLAB also has methods for modifying the appearance of the plot using commands.
FIGURE 6-2: You can do anything with commands that you can do with the GUI.
Creating a plot using the Workspace window
The Workspace window displays all the variables that you create, no matter what type they might be. What you may not realize is that you can right-click any of these variables and create a plot from them. (If you don’t see your plot listed, select the Plot Catalog option on the context menu to see a full listing of the available plots.) The following steps help you create a variable and then plot it using the Workspace window functionality.
1. Type y = [5, 10, 22, 6, 17]; and press Enter in the Command Window.
You see the variable y appear in the Workspace window.
2. Right-click y in the Workspace window and choosebar(y) from the context menu that appears.
MATLAB creates a bar graph using the default settings, as shown in Figure 6-3. Notice that MATLAB labels this bar graph Figure 1.
Even though this method might seem really limited, it’s a great way to create a quick visualization of data so that you can see patterns or understand how the various data points interact. The advantage of this method is that it’s quite fast. In addition, the output varies based on the data you provide. For example, try the example using y1 = [5, 10, 22, 6, 17; 2, 8, 7, 19, 21]; (row-oriented) and y2 = [5, 10, 22, 6, 17; 2, 8, 7, 19, 21]'; (column-oriented) to see a difference.
FIGURE 6-3: Bar graphs are best used for a few discrete values that you want to compare.
MATLAB overwrites the previous plot you create when you create a new plot, unless you use the hold command that is described later in the chapter. If you created the examples in the previous section, you should note that all the plots have appeared in the Figure 1 window and that no new plot windows have been created. Your old plot is immediately overwritten when you create a new one unless you save the old plot to disk or use the hold command.
Creating a plot using the Plots tab options
When you view the Plots tab in MATLAB, you see a gallery of the kinds of plots you can create. You initially see just a few of the available plots. However, if you click the downward-pointing arrow button at the right side of the gallery, you see a selection of plot types like the one shown in Figure 6-4.
Note the option buttons at the bottom with Plots for y currently selected. The default is to show only the plots you can use with the currently selected data. If you choose All Plots instead, the list will also show plots that need additional input, such as a contour plot in this case. Unusable plots appear grayed out. Hover your mouse over the plot entry for a few seconds to determine what you need to use the plot, such as a matrix for the contour plot. The All Plots option is helpful when you try to remember a plot and can’t seem to find it in the standard list.
To use this feature, select a variable in the Workspace window and then choose one of the plots from the gallery list. This is the technique to use if you can’t quite remember what sort of plot you want to create (making the command option less convenient), or if the option doesn’t appear in the Workspace window context menu. For example, you might want to create a horizontal bar plot using variable y. To perform this task, simply click variable y in the Workspace window and then choose barh in the MATLAB Bar Plots section of the gallery. The output that MATLAB comes up with looks like Figure 6-5.
FIGURE 6-4: MATLAB comes with a large number of plot types that you can use.
FIGURE 6-5: The Plots tab contains options that don’t appear on the Workspace context menu.
Using the Plot Function
The plot() function provides you with considerable flexibility in using commands to create and modify a plot. As a minimum, you supply two vectors: one for the x-axis and one for the y-axis. However, you can provide more information to adjust the appearance of the resulting plot. The following sections provide additional details on how to work with the plot() function and make it provide the output you want.
Working with line color, markers, and line style
The plot() function can actually accommodate values in groups of three: the x-axis, the y-axis, and a character string that specifies the line color, marker style, and line style. Table 6-1 shows the values for the character string; you’d use values from each of the three entries (x-axis, y-axis, character string) to change the appearance of the plot.
TABLE 6-1 Line Color, Data Point Style, and Line Style
Color |
Marker |
Style |
|||
Code |
Line Color |
Code |
Marker Style |
Code |
Line Style |
b |
blue |
. |
point |
- |
Solid |
g |
green |
o |
circle |
: |
Dotted |
r |
red |
x |
x-mark |
-. |
dash dot |
c |
cyan |
+ |
plus |
-- |
Dashed |
m |
magenta |
* |
star |
(none) |
no line |
y |
yellow |
s |
square |
||
k |
black |
d |
diamond |
||
w |
white |
v |
down triangle |
||
^ |
up triangle |
||||
< |
left triangle |
||||
> |
right triangle |
||||
p |
5 point star |
||||
h |
6 point star |
You can combine the entries in various ways. For example, type plot(1:length(y), y, 'r+--') and press Enter to obtain the plot shown in Figure 6-6. Note that the 1:length(y) argument creates a vector with the values 1 through 5. Even though you can’t see it in the book, the line is red. The markers show up as plus signs, and the line is dashed, as you might expect. Note that the vectors must be the same length, or you see an error message, so creating a range of 1 to length(y) prevents the error message.
FIGURE 6-6: Spruce up your plot using styles.
Creating multiple plots in a single command
In many cases, you need to plot more than one set of data points when working with a plot. The plot() function can accommodate as many series as needed to display all your data. For example, you might want to plot both sine and cosine of x to compare them. To perform this task, you type plot(x, sin(x), 'g-', x, cos(x), 'b-') and press Enter (remember that x was defined earlier as x = -pi:0.01:pi;). Figure 6-7 shows the result.
In this case, sine appears as a green solid line. The value of cosine is in blue with a solid line. Notice that each series appears in the plot() command as three values: x-axis, y-axis, and format string. You can add as many series as needed to complete your plot.
FIGURE 6-7: Plot multiple series when necessary.
Modifying Any Plot
At some point, you’ll want to change the content of your plot. Perhaps you want to add a legend or change how the data is presented. After you get the data looking just right, you might need to label certain items or perform other tasks to make the output look nicer. You can modify any plot you create using either commands or the MATLAB GUI.
The modification method that you use is entirely up to you. Some people work better at the keyboard, others using the mouse, and still others using a combination of the two. Working at the keyboard is a lot faster but requires that you memorize the commands to type. The GUI provides you with great memory aids, but working with the mouse is slower, and you might not be able to find a particular property you want to change when it becomes buried in a menu somewhere. The following sections describe techniques to use for modifying any plot.
Making simple changes
You can make a number of simple changes to your plot that don’t require any special handling other than to type the command. For example, to add a grid to an existing plot, you simply type grid on and press Enter. (MATLAB has a number of grid commands. For example, grid MINOR toggles the minor grid lines. Type help grid and press Enter to obtain additional information.)
Adding a legend means typing a name for each of the plots. For example, if you want to add a legend to the plot in Figure 6-7, you type legend('Sine', 'Cosine') and press Enter. You can also change items such as the legend orientation. The default orientation is vertical, but you can change it to horizontal by typing legend('orientation', 'horizontal') and pressing Enter. Notice that the property name comes first, followed by the property value. There are other properties that control location; you access these by typing commands like legend('location', 'northwest') and pressing Enter. The idea is to keep the legend out of the way.
MATLAB also lets you add titles to various parts of the plot. For example, to give the plot a title, type title('Sine and Cosine') and press Enter. You can also provide labels for the x-axis using xlabel() and for the y-axis using ylable(). The point is that you have full control over the appearance of the plot. Figure 6-8 shows the effects of the commands that you have tried so far. (Compare it to Figure 6-7.)
FIGURE 6-8: Change your plot setup using commands.
If you make a mistake, you can always clear the current plot by using the clf command (don’t use it now, you’ll mess up your plot for future sections). The clf command does for the plot what the clc command does for the Command Window. Make sure that you actually want to clear the plot before using the clf command because there isn’t any sort of undo feature to restore the plot.
Adding to a plot
You may decide that you want to add another plot to an existing plot. For example, you might want to plot the square of x for each of the values used in the previous examples. To make this technique work, you need to perform the three-step process described here:
1. Type hold on and press Enter.
If you try to add another plot without placing a hold on the current plot, MATLAB simply creates a new plot and gets rid of the old one. The hold on command lets you retain the current plot while you add something to it. Using hold by itself toggles the hold state, and you can use hold off to return MATLAB to its default state of overwriting the current plot each time you generate a new one.
2. Type newplot = plot(x, power(x, 2), ′m:′) and press Enter.
This command creates a new plot and places a handle to that plot in newplot. A handle is just what it sounds like — a means of obtaining access to the plot you just created. If you don’t store the plot handle, you can’t access it later.
Note that the legend automatically adds a new member called data1. However, data1 isn’t very descriptive, so you need to change it by issuing another call to legend().
3. Type legend('Sine', 'Cosine', ['${x}^{2}$'], 'interpreter', 'latex') and press Enter.
This rather odd-looking command contains a number of essential parts. The sine and cosine values are the same as before, but ['${x}^{2}$'] produces the output x^{2}, where the 2 is superscripted. To see special formatted characters, you need to use the LaTeX interpreter, as described at https://www.mathworks.com/help/matlab/creating_plots/greek-letters-and-special-characters-in-graph-text.html. Using LaTeX allows you to add special characters as well. Figure 6-9 shows the updated output.
The sine and cosine still have the same values, but the new plot has much larger values, so the previous plot lines appear to have shrunk. However, compare the values in Figures 6-8 and 6-9 and you see that the values of sine and cosine are the same.
4. Type hold off and press Enter.
The hold off command releases the plot. To create new plots, you must release your hold on the existing plot.
FIGURE 6-9: Add a new plot to the existing setup.
USING THE FIGURE() FUNCTION
This chapter concentrates on various sorts of plots because plots provide you with output. However, the figure() function can be an important part of your toolbox when you start creating scripts. You use the figure() function alone to create a new figure (an object containing graphics, such as plots, that might be displayed in a separate window) doesn’t have any sort of information in it. The advantage is that you can then fill the new figure with anything you want. In addition, the figure() function creates a new figure without overwriting the old one. The figure() function returns a handle to the figure rather than to the plot inside the figure. If you have multiple plots inside a figure, you can use the figure handle to select all the plots rather than just one of them.
You use the figure() function with a handle to make the figure associated with a particular handle the current figure. For example, the figure(MyFigure) command would make the figure pointed to by MyFigure the current figure. When working with multiple figures, you need some method of selecting between them, and the figure() function provides the best method of doing that.
Of course, you might have created the figure as a plot rather than as a figure. The plot handle doesn’t work with the figure() function. Use the gcf() (Get Current Figure) function to obtain the figure handle for any figure you create using a plot. You can then save the figure handle in a variable for later use.
Deleting a plot
You might decide that you really don’t want to keep a plot you’ve added. In this case, you need a handle to the plot you want to remove, such as the handle stored as part of the steps in the previous section. To remove the plot, type delete(newplot) and press Enter. MATLAB removes the plot from the display.
Working with subplots
Figure 6-9, which appears in the previous section, shows three plots — one on top of the other. You don’t have to display the plots in this manner. Instead, you can display them side by side (or even in a grid). To make this happen, you use the subplots feature of MATLAB. A subplot is simply a plot that takes up only a portion of the display.
Creating a subplot
The best way to understand subplots is to see them in action. The following steps help you create the three previous plots as subplots:
1. Type clf and press Enter.
MATLAB clears any previous plot you created.
2. Type subplot(1, 3, 1) and press Enter.
This function creates a grid consisting of one row and three columns. It tells MATLAB to place the first plot in the first space in the grid. You see the blank space for the plot.
3. Type p1 = plot(x, sin(x), 'g-') and press Enter.
You see the first plot added to the display.
Notice that the example is creating the plots one at a time. You can’t combine plots in a single call when using subplots. In addition, you need to maintain a handle to each of the plots in order to configure them.
4. Type subplot(1, 3, 2) and press Enter.
MATLAB selects the second area for the next plot.
5. Type p2 = plot(x, cos(x),′b-′) and press Enter.
You see the second plot added to the display.
6. Type subplot(1, 3, 3) and press Enter.
MATLAB selects the third area for the next plot.
7. Type p3 = plot(x, power(x, 2), ′m:′) and press Enter.
You see the third plot added to the display, as shown in Figure 6-10.
Each plot takes up the entire area allocated to it. You can’t compare plots easily because each plot is in its own space and uses its own units of measure. However, this approach does have the advantage of letting you see each plot clearly.
FIGURE 6-10: Each plot appears in its own area.
Changing subplot information
The subplot() function doesn’t change anything — it merely selects something. For example, the plots in Figure 6-10 lack titles. To add a title to the first plot, follow these steps:
1. Type subplot(1, 3, 1) and press Enter.
MATLAB selects the first subplot.
2. Type title(′Sine′) and press Enter.
You see a title added to the first subplot.
Configuring individual plots
To work with a subplot in any meaningful way, you need to have a handle to the subplot. The following steps describe how to change the color and line type of the second plot:
1. Type subplot(1, 3, 2) and press Enter.
MATLAB selects the second subplot. Even though the handle used with the set() command in the following step will select the subplot for you, this step is added so that you can actually see MATLAB select the subplot. In some cases, performing this task as a separate step is helpful to ensure that any function calls that follow use the correct subplot, even when these function calls don’t include a handle. Later, when you start creating scripts, you find that errors creep into scripts when you’re making assumptions about which plot is selected, rather than knowing for sure which plot is selected.
2. Type set(p2, ′color′, ′r′) and press Enter.
The line color is now red. The set() function accepts a handle to a plot or another MATLAB object as the first value, the name of a property as the second, and the new value for that property as the third. This function call tells MATLAB to change the color property of the line pointed at by p2 to red.
3. Type set(p2, ′LineStyle′, ′ -.′) and press Enter.
The LineStyle property for the cosine plot is now set to dash dot, as shown in Figure 6-11. Note that you can find additional properties in the Chart Objects section at https://www.mathworks.com/help/matlab/line-plots.html?s_tid=CRUX_lftnav.
FIGURE 6-11: Changing line-specific features requires a handle to that line.
Plotting with 2D Information
MATLAB has built-in plotting routines that are suitable for many types of data and applications. Table 6-2 gives you an overview of various 2D plotting functions, including what they plot and how they’re commonly used. You use these functions in place of the plot() function used throughout the chapter to create plots. The output will contain the kind of plot you have requested, such as a pie chart when using the pie() function. (MATLAB also supports 3D plotting; for more on that aspect of plotting, check out Chapter 7.)
TABLE 6-2 MATLAB Plotting Routines
Routine |
What It Plots |
Used By |
plotyy() |
Data with two y axes |
Business users rely on this plot to show two sets of units, for example, quantity sold and money. |
loglog() |
Data with both x and y axes as log scales |
Science, Technology, Engineering, and Mathematics (STEM) users rely on this plot to show power or root dependence of y versus x. |
semilogx() |
Data with x-axis log scale |
STEM users rely on this plot to show logarithmic dependence of y versus x. |
semilogy() |
Data with y-axis log scale |
STEM and social science users rely on this plot to show exponential dependence of y versus x and population growth (as an example). |
scatter() |
Data in x-y pairs |
Experimentalists and statisticians rely on this plot to show patterns created by the individual data points. |
hist() |
Frequency of occurrence of particular values of data |
Experimentalists and statisticians rely on this plot to understand imprecision and inaccuracy. |
area() |
x-y data with areas filled in |
Business and STEM users rely on this plot to see (and understand) the contributions of parts to a whole. |
pie() |
Set of labeled numbers |
Business users rely on this plot to see (and understand) the fractional contributions of each part to a whole. |
ezpolar() |
Data in terms of radius and angle |
STEM users rely on this plot to show the angular dependence of information. |