Chapter 7
IN THIS CHAPTER
Working with 3D plots
Creating enhanced plots
Employing plot extras
Chapter 6 helps you create plots that convey 2D data in visual form. Using plots in this manner helps you present the data in a way that most humans understand better than abstract numbers. Visual presentations are concrete and help the viewer see patterns that might be invisible otherwise. The 3D plots described in this chapter do the same thing as those 2D plots, only with a 3D data set. The viewer sees depth as well as height and width when looking at that data. Using a 3D data set can greatly improve the amount of information the user obtains from a plot. For example, a 3D plot could present the variation of a data set over time so that the user gains insights into how the data set changes.
If you worked through Chapter 6, you focused mostly on small changes to improve the aesthetics of your plots. This chapter looks at some of the fancier things you can do to make plots even more appealing. In many cases, nontechnical viewers require these sorts of additions in order to appreciate the data you present. Making data as interesting as possible can only help to improve your presentation and convince others to accept your interpretation of the data. Of course, making plots that look nice is also just plain fun, and everyone could use a little more fun in their creation and presentation of data.
The last part of this chapter helps you work with plots at a lower level to create better visual effects or to perform manipulations that would be hard otherwise. For example, you discover more about working with the plot axes to enhance plot visualizations. These more advanced plot techniques are good to know, especially if you work with complex data, but you can also skip this last section until you actually need the advanced functionality it discusses.
Plotting with 3D Information
A 3D plot has an x-, y-, and z-axis (height, width, and depth, if you prefer). The addition of depth lets you present more information to the viewer. For example, you could present historical information about a plot so that each element along the z-axis is a different date. Of course, the z-axis, like the x and y axes, can represent anything you want. The thing to remember is that you now have another method of presenting information to the viewer.
It’s also important to consider that you’re presenting 3D information on a 2D surface — the computer screen or a piece of paper. Some users forget this fact and find that some of their data hides behind another plot object that is greater in magnitude. When working with 3D plots, you need to arrange the information in such a manner that you can see it all onscreen.
The following sections describe various kinds of plots and how to create them. Each plot type has specific uses and lends itself to particular kinds of data display. Of course, the kind of plot you choose depends on how you want to present the data as well.
Using the bar() function to obtain a flat 3D plot
The bar chart is a standard form of presentation that is mostly used in a business environment. You can use a bar chart to display either 2D or 3D data. When you feed a bar chart a vector, it produces a 2D bar chart. Providing a bar chart with a matrix produces a 3D chart. The following steps help you create a 3D bar chart:
1. Type SurveyData = [8, 7, 6; 13, 21, 15; 32, 27, 32] and press Enter.
MATLAB creates a new matrix named SurveyData that is used for many of the examples in this chapter. You see the following output:
SurveyData =
8 7 6
13 21 15
32 27 32
2. Type bar(SurveyData) and press Enter.
You see a flat presentation of SurveyData, as shown in Figure 7-1. The x-axis shows each of the columns in turn. (If you could see colors in the book, you would see that the first column is blue, the second is red, and the third is yellow.) The y-axis presents the value of each cell (such as 8, 7, and 6 for the first SurveyData row). The z-axis presents each row in a group, and each group corresponds to a number between 1 and 3.
FIGURE 7-1: A flat presentation of the x, y, and z axes of SurveyData.
3. Type Bar1 = bar(SurveyData, 'stacked') and press Enter.
You see the same SurveyData matrix presented as a stacked bar chart, as shown in Figure 7-2. In this case, the x-axis elements are shown stacked one on top of the other.
The example also outputs information about the bar chart handles (a means of obtaining access to the plot). The values may differ, but you should see three handles output like the following (each handle is named Bar; previous versions of MATLAB used a number to represent the handle in the output):
Bar1 =
1x3 Bar array:
Bar Bar Bar
FIGURE 7-2: A stacked presentation of the SurveyData matrix.
Each of the z-axis elements has its own handle that you use to manipulate it. This is an important part of working with the bar chart later when you want to modify something.
Figures 7-1 and 7-2 present two forms of the same data. The bar() function provides you with several alternative presentations:
· grouped: This is the default setting shown in Figure 7-1.
· hist: The data appears much like in Figure 7-1, except that no spaces appear between the bars for a particular group. The groups do still have spaces between them.
· hisc: The groups are positioned so that each group starts at a number on the x-axis, rather than being centered on it.
· stacked: This is the stacked appearance shown in Figure 7-2.
4. Type get(Bar1(1)) and press Enter.
The get() function obtains the properties you can work with for a particular object. In this case, you request Bar1(1), which is the first group in Figure 7-2. In other words, this would be the first member of the z-axis. You see the following output:
Annotation: [1×1 matlab.graphics.
eventdata.Annotation]
BarLayout: 'stacked'
BarWidth: 0.8000
BaseLine: [1×1 Baseline]
BaseValue: 0
BeingDeleted: off
BusyAction: 'queue'
ButtonDownFcn: ''
CData: [3×3 double]
Children: [0×0 GraphicsPlaceholder]
Clipping: on
ContextMenu: [0×0 GraphicsPlaceholder]
CreateFcn: ''
DataTipTemplate: [1×1 matlab.graphics.
datatip.DataTipTemplate]
DeleteFcn: ''
DisplayName: ''
EdgeAlpha: 1
EdgeColor: [0 0 0]
FaceAlpha: 1
FaceColor: [0 0.4470 0.7410]
FaceColorMode: 'auto'
HandleVisibility: 'on'
HitTest: on
Horizontal: off
Interruptible: on
LineStyle: '-'
LineWidth: 0.5000
Parent: [1×1 Axes]
PickableParts: 'visible'
Selected: off
SelectionHighlight: on
SeriesIndex: 1
ShowBaseLine: on
Tag: ''
Type: 'bar'
UserData: []
Visible: on
XData: [1 2 3]
XDataMode: 'auto'
XDataSource: ''
XEndPoints: [1 2 3]
YData: [8 13 32]
YDataSource: ''
YEndPoints: [8 13 32]
After you know the properties that you can modify for any MATLAB object, you can use those properties to start building scripts. (You created your first script in Chapter 2.) Just creating and then playing with objects is a good way to discover just what MATLAB has to offer. Many of these properties will appear foreign to you and you don’t have to worry about them, but notice that the YData property contains a vector with the three data points for this particular bar.
It’s also possible to obtain individual property values. For example, if you use the get(Bar1(1), 'YData') command, you see the current YData values for just the first bar.
5. Type set(Bar1(1), 'YData', [40, 40, 40]) and press Enter.
The set() function lets you modify the property values that you see when using the get() function. In this case, you modify the YData property for the first bar — the blue objects when you see the plot onscreen. Figure 7-3 shows the result of the modification.
FIGURE 7-3: Rather than re-create a plot, you can simply modify values to obtain the result you want.
Using bar3() to obtain a dimensional 3D plot
The flat form of the 3D plot is nice, but it lacks pizzazz. When you present your information to other engineers and scientists, the accuracy of the flat version is welcome. Everyone can see the 3D data clearly and work with it productively. A business viewer might want something a bit different. In this case, presenting a pseudo-3D look is better because the business user gets a better overall view of the data. Precise measurements aren’t quite as useful in this case — but seeing how the data relate to each other is. To create a dimensional plot of the data that appears in the previous section, type Bar2 = bar3(SurveyData) and press Enter. You see a result similar to the one shown in Figure 7-4.
FIGURE 7-4: Dimensional plots display the relationships between data well.
The two problems with the presentation in Figure 7-4 are that you can’t see some of the data, and none of it is presented to best effect. To rotate the image, you use the view() function. The view() function can accept either x, y, and z rotation in degrees, or a combination of azimuth and elevation. Using x, y, and z rotation is easier for most people than trying to figure out azimuth and elevation. To change Figure 7-4 so that you can more easily see the bars, type view([-45, 45, 30]) and press Enter. Figure 7-5 shows the result.
The view() function uses absolute rotation rather than relative rotation, in which one change would affect the next. As a result, if you type view([-45, 45, 30]) and press Enter a second time, you obtain the same result as before. To obtain a new view, you must provide different values.
As an alternative to using the view() function, you can also click the Rotate 3D button, shown in Figure 7-5. It’s the button with the circular arrow that appears to the left of the hand (pan) icon. Although the view() function is more precise and lets you make changes to the view without moving your hands from the keyboard, the Rotate 3D button can be faster and easier.
FIGURE 7-5: Changing the view makes seeing the data easier.
Using barh() and more
MATLAB provides you with a number of 3D plotting functions that you use to obtain various effects. The barh(), bar3(), and bar3h() functions work just like the bar() function except that they display slightly differently. Closely related are the hist(), histc(), rose(), polar(), and pareto() functions. Table 7-1 lists the various plotting functions that you have at your disposal as well as a brief description of how they work.
TABLE 7-1 Bar Procedures and Other Related Plotting Procedures
Function |
What It Does |
Examples |
bar() |
Plots a flat bar chart that relies on color and grouping to show the z-axis. |
bar(SurveyData) bar(SurveyData', 'stacked') |
bar3() |
Plots a dimensional bar chart that uses color and perspective to show the z-axis. |
bar3(SurveyData) bar3(SurveyData','stacked') |
bar3h() |
Plots a horizontal dimensional bar chart that uses color and perspective to show the z-axis. |
bar3h(SurveyData) bar3h(SurveyData','stacked') |
barh() |
Plots a horizontal flat bar chart that relies on color and grouping to show the z-axis. |
barh(SurveyData) barh(SurveyData','stacked') |
hist() |
Plots frequency of occurrence for bins given raw data and, optionally, bin centers. |
hist(randn(1,100), 5) creates 100 normally distributed random numbers and places them in five equally spaced bins. hist(randn(1,100),[-3.5,-2.5,-1.5,-.5,.5,1.5,2.5,3.5]) creates 100 normally distributed numbers and places them in specific bin centers. |
histc() |
Obtains frequency data for each bin and displays it as text (rather than as a plot). The advantage is that you can specify bin edges. |
histc(randn(1,100), [-4:1:4]) specifies bins that are 1 unit wide, with edges on integers starting at –4. You could use this information in a plot as bar([-4:1:4],ans,'histc'). |
pareto() |
Plots a bar chart ordered by highest bars first — used in business to identify factors causing the greatest effect. |
histc(randn(1,100),[-4:1:4]) pareto(ans) |
polar() |
Plots a polar display of data in which the rings of the circle represent individual data values. |
histc(randn(1,100),[-4:1:4]) polar(ans) |
rose() |
Plots data bars versus angles in a polar-like display. As with the hist() function, you may also specify bin centers. |
rose(randn(1,100), 5) creates 100 normally distributed numbers and places them in five equally spaced bins. |
Enhancing Your Plots
For visual information to be meaningful and more informative, you need to add titles, labels, legends, and other enhancements to plots of any type (both 3D and 2D). (The greater visual appeal of 3D plots only makes the plot prettier, not more informative.) The following sections of the chapter won’t make you into a graphic designer, but they will let you create more interesting plots that you can use to help others understand your data. The goal of these sections is to help you promote better communication. The examples in the following sections rely on the 3D plot you created in the “Using bar3() to obtain a dimensional 3D plot” section, earlier in this chapter.
Getting an axes handle
Before you can do anything, you need a handle to the current axes. The best way to obtain such a handle (assuming that you have a figure displayed, such as the one in Figure 7-5) is to type Bar2Axes = gca() (Get Current Axes) and press Enter. The gca() function returns the handle for the current plot. When you type get(Bar2Axes) and press Enter, you see the properties associated with the current plot.
TRICKS OF THE TRADE FOR WORKING WITH FIGURES
Knowing a few tricks is helpful when working with plots. The tricks help you perform work faster and more efficiently. In addition, they make working with plots more fun. The following list contains tips that you can try on your own figures, but don’t use them with the current examples.
· Start over by using the clf command, which stands for Clear Figure (which is precisely what it does).
· Stay organized by obtaining a handle (a method to gain access to the figure) using the gcf() (Get Current Figure) function. Don’t confuse the figure handle with the plot handle mentioned earlier — a figure contains one or more plots, so the figure handle is different.
· Make a particular figure the current figure, use the figure() function with the variable containing the figure handle.
· Reset figures to default values using the reset() function with the variable containing the figure handle. This feature comes in handy when the changes you make produce undesirable results.
· See the properties associated with the current figure by using the get() function with the variable containing the figure handle. MATLAB displays a list of the properties and their current values. If a property doesn’t have a value, the value is left blank.
Modifying axes labels
MATLAB automatically creates labels for some of the axes for you. However, the labels are generic and don’t really say anything. To modify anything on the axes, you need an axes handle (as described in the previous section).
After you have the handle, you use the appropriate properties to modify the appearance of the axes. For example, to modify the x-axis label, you type xlabel(Bar2Axes, 'X Axis') and press Enter. Similarly, for the y-axis, you type ylabel(Bar2Axes, 'Y Axis') and press Enter. You can also use the zlabel() function for the z-axis.
Each of the ticks on an axis can have a different label as well. The default is to simply assign them numbers. However, if you want to assign meaningful names to the x-axis ticks, you can type set(Bar2Axes, 'XTickLabel', {'Yesterday', 'Today', 'Tomorrow'}) and press Enter. Notice that the labels appear within a cell array using curly brackets ({}). Likewise, to set the y-axis ticks, you can type set(Bar2Axes, 'YTickLabel', {'Area 1', 'Area 2', 'Area3'}) and press Enter. You can also use a ZTickLabel property, which you can modify. The tick mark labels will repeat if you don’t provide enough labels for each tick mark.
To control the tick values, you type set(Bar2Axes, 'ZTick', [0, 5, 10, 15, 20, 25, 30, 35, 40]) and press Enter. Those two axes also have XTick and YTick properties. Of course, in order to see the z-axis ticks, you also need to change the limit (the size of the plot in that direction). To perform this task, you type set(Bar2Axes, 'ZLim', [0 45]) and press Enter.
Many of the set() function commands have alternatives. For example, you can change the ZLim property by using the zlim() function. The alternative command in this case is zlim(Bar2Axes, [0 45]). Using a set() function does have the advantage of making it easier to enter the changes because you have to remember only one function name. However, the result is the same no matter which approach you use, so it’s entirely a matter of personal preference.
Use the get() function whenever necessary to discover additional interesting properties to work with. Properties are available to control every aspect of the axes’ display. For example, if you want to change the color of the axes’ labels, you use the XColor, YColor, and ZColor properties. Figure 7-6 shows the results of the changes in this section.
FIGURE 7-6: Properties control the appearance of the axes in your plot.
Many properties have an automatic setting. For example, to modify the ZLim property so that it uses the automatic setting, you type zlim(Bar2Axes, 'auto') and press Enter. The alternative when using a set() function is to type set(Bar2Axes, 'ZLimMode', 'auto') and press Enter. Notice that when you use the zlim() function, you can set either the values or the mode using the same command. When using the set() function, you use different properties (ZLim and ZLimMode) to perform the task. However, the important thing to remember is that the auto mode tells MATLAB to configure these items automatically for you.
Using commands to change plot properties is fast and precise because your hands never leave the keyboard and you don’t spend a lot of time searching for a property to change in the GUI. However, you can always change properties using the GUI as well. Click the Edit Plot button (the one that looks like a hollow arrow on the Figure Toolbar in Figure 7-5) to put the figure into edit mode. Click the element you want to modify to select it. Right-click the selected element and choose Open Property Editor to modify the properties associated with that particular element.
Adding a title
Every plot should have a title to describe what the plot is about. You use the title() function to add a title. However, the title() function accepts all sorts of properties so that you can make the title look precisely the way you want. To see how this function works, type title(Bar2Axes, 'Sample Plot', 'FontName', 'Times', 'FontSize', 22, 'Color', [.5, 0, .5], 'BackgroundColor', [1, 1, 1], 'EdgeColor', [0, 0, 0], 'LineWidth', 2, 'Margin', 4) and press Enter. MATLAB changes the title, as shown in Figure 7-7.
Interestingly enough, most of the plot objects support these properties, but the title uses them most often. Here’s a list of the properties you just changed:
· FontName: Provides the text name of a font you want to use. It can be the name of any font that is stored on the host system.
· FontSize: Specifies the actual size of the font (in points by default). A larger number creates a larger font.
· Color: Determines the color of the text in the title. This property requires three input values for red, green, and blue. The values must be between 0 and 1. You can use fractional values and mix colors as needed to produce specific results. An entry of all zeros produces black; an entry of all ones produces white.
· BackgroundColor: Determines the color of the background behind the text in the title. It uses the same color scheme as the Color property.
· EdgeColor: Determines the color of any line surrounding the title. It uses the same color scheme as the Color property.
· LineWidth: Creates a line around the title of a particular width (in points by default).
· Margin: Adds space between the line surrounding the title (the edge) and the text (in points by default).
FIGURE 7-7: A title can use properties to create a pleasing appearance.
Rotating label text
In some cases, the text added to a plot just doesn’t look right because it doesn’t quite reflect the orientation of the plot itself. The title in Figure 7-7 looks just fine, but the x-axis and y-axis labels look slightly askew. You can modify them so that they look better.
When you review some properties using the get() function, you see a handle value instead of an actual value. For example, when you look at the XLabel value, you see a handle that lets you work more intimately with the underlying label. To see this value, you use the get(Bar2Axes, 'XLabel') command. If you don’t want to use a variable to hold the handle, you can see the XLabel properties by typing get(get(Bar2Axes, 'XLabel')) and pressing Enter. What you’re telling MATLAB to do is to get the properties that are pointed to by the XLabel value obtained with the Bar2Axes handle — essentially, a handle within a handle.
One of the properties within XLabel is Rotation, which controls the angle at which the text is displayed. To change how the plot looks, type set(get(Bar2Axes, 'XLabel'), 'Rotation', -30) and press Enter. The x-axis label is now aligned with the plot. You can do the same thing with the y-axis label by typing set(get(Bar2Axes, 'YLabel'), 'Rotation', 30) and pressing Enter.
You can also reposition the labels, although using the GUI to perform this task is probably easier. However, the Position property provides you with access to this feature. To see the starting position of the x-axis label, type get(get(Bar2Axes, 'XLabel'), 'Position') and press Enter. The example setup shows the following output (your output may differ):
ans =
2.2433 -0.5489 -7.4167
Small tweaks work best, so based on these readings, you might want to change the settings from 2.2433 to 2.16, from -0.5489 to -0.4, and from -7.4167 to -7. Type set(get(Bar2Axes, 'XLabel'), 'Position', [2.16 -0.4 -7]) and press Enter to better position the x-axis label. (You may need to fiddle with the numbers a bit to get your plot to match the one in the book, and your final result may not look precisely like the screenshot.) After a little fiddling, your X Axis label should look like the one in Figure 7-8.
FIGURE 7-8: Any object can be rotated and repositioned as necessary.
Employing annotations
Annotations let you add additional information to a plot. For example, you might want to put a circle around a particular data point or use an arrow to point to a particular bar as part of your presentation. Of course, you may simply want to add some sort of emphasis to the plot using artistic elements. No matter how you want to work with annotations, you have access to these drawing elements:
· Line
· Arrow
· Text Arrow
· Double Arrow
· Textbox
· Rectangle
· Ellipse
To add annotations to your figure, you use the annotation() function. Say you want to point out that Area 3 in Figure 7-8 is the best area of the group. To add the text area, you type TArrow = annotation('textarrow', [.7, .55], [.9, .77], 'String', 'Area 3 is the best!') and press Enter. You see the result shown in Figure 7-9. This version of the annotation() function accepts the annotation type, the x location, y location, property name (String), and property value (Area 3 is the best!).
FIGURE 7-9: Add annotations to document your plot for others.
The annotations don’t all use precisely the same command format. For example, when you want to add a textbox, you provide the starting location, height, and width, all within the same vector. To see this version of the annotation() function in action, type TBox = annotation('textbox', [.1, .8, .11, .16], 'String', 'Areas Report', 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle') and press Enter. In this case, you center the text within the box and place it in the upper-left corner. A textbox doesn’t point to anything — it simply displays information, as shown in Figure 7-10.
FIGURE 7-10: Annotations don’t use a consistent argument setup.
Printing your plot
At some point, you probably need to print your plot. You have a number of choices in creating output. The following list provides you with a quick overview of the options at your disposal:
· At the Figure window, select File ⇒ Print to display the Print dialog box. Select the options you want to use for printing.
· At the Figure window, type Ctrl+P to display the Print dialog box. Select the options you want to use for printing.
· Click the Print Figure button (with the printer icon) on the figure’s Figure toolbar (the default toolbar).
· At the Command Window, type print() and press Enter.
· Using print() alone prints the entire figure, including any subplots.
· Adding a handle to print(), such as print(Bar2), prints only the object associated with the handle.
In some cases, you may want to output your plot in a form that lets you print it in another location. When working in the Figure window, you select the Print to File option in the Print dialog box. MATLAB will ask you to provide a filename for printing. When working in the Command Window, you supply a filename as a second argument to the print() function. For example, you might use print(Bar2, 'MyFile.prn') as the command.
Using the Plot Extras
Chapter 6 discusses commands like grid on, which is used to display a grid on your plot. Earlier in this chapter, you discover essentials like adding annotation to your plot. The “Getting an axes handle” section tells you specifically about working with axes at a basic level. The following sections describe the kinds of extras you can use for emphasizing specific data. For example, the way in which you configure the grid can help make differences between data more obvious.
You can always clear the current figure from the window by typing cla and pressing Enter. This command clears all the plot information from the figure, but doesn’t close the figure window.
Creating axes dates using datetick()
You use datetick() to add dates to a plot axis. When using datetick(), you need an axis that has numbers that are in the range of the dates you need. For example, when you type datenum('9,15,2020') and press Enter, you get an output value of 738049. When datetick() sees this value, it converts the number to a date.
The datenum() function also accepts time as input. When you type datenum('09/15/2020 08:00:00 AM') and press Enter, you get 738049.333333333 as output (assuming that you first type format longG and press Enter). Notice that the integer portion of the value is the same as before, but the decimal portion has changed to show the time. If you don’t provide a time, the output is for midnight of the day you select. You can convert a numeric date back to a string date using the datestr() function.
The x-axis in this example uses date values. To create an x-axis data source, type XSource = linspace(datenum('09/15/2020'), datenum('09/19/2020'), 5); and press Enter. This act creates a vector that contains the numeric version of dates from 09/15/2020 to 09/19/2020. The linspace() function returns a vector that contains the specified number of value (5 in this case) between the two values you specify.
To create the y-axis data source, type YSource = [1, 5, 9, 4, 3]; and press Enter. Type Bar1 = bar(XSource, YSource) and press Enter to create the required plot. The default tick spacing may show too many points, so type set(gca, 'XTick', linspace(datenum('09/15/2020'), datenum('09/19/2020'), 5)) and press Enter to set the tick spacing. Notice that the x-axis doesn’t use the normal numbering scheme that begins with 1 — it uses a date number instead (expressed as an exponent rather than an integer). Even though the x-axis numbers look the same, you see in the next paragraph that they aren’t.
To turn the x-axis labels into dates, you now use the datetick() function. Type datetick('x', 'dd mmm yy', 'keeplimits', 'keepticks') and press Enter. Figure 7-11 shows the plot with dates in place.
FIGURE 7-11: Creating dates in a specific format.
All the arguments used with datetick() are optional. When you use datetick() by itself, the output appears on the x-axis using a two-digit month and a two-digit day. The end points also have dates, so instead of seeing just five dates, you see seven (one each for the ends). The example uses the following arguments in this order to modify how datetick() normally works:
· Axis: Determines which axis to use. You can choose the x-, y-, or z-axis (when working with a 3D plot).
· Date format: Specifies how the date should appear. You can either use a string containing the format as characters or numeric values, as shown at https://www.mathworks.com/help/matlab/ref/datetick.html#btpmlwj-1-dateFormat. (You can also type help datetick and press Enter to obtain a listing of date formats.) Using characters tends to be clearer, but using numbers tends to save space and time.
· 'keeplimits': Prevents MATLAB from adding entries to either end of the axis. This means that the example plot retains five x-axis entries rather than getting seven.
· 'keepticks': Prevents MATLAB from changing the value of the ticks.
Creating plots with colorbar()
Using a color bar with your plot can help people see data values based on color rather than pure numeric value. The color bar itself can assign human-understandable values to the numeric data so that the data means something to those viewing it. The best way to work with color bars is to see them in action. The following steps help you create a color bar by using the colorbar() function and use it to define values in a bar chart:
1. Type YSource = [4, 2, 5, 6; 1, 2, 4, 3]; and press Enter.
MATLAB creates a new data source for the plot.
2. Type Bar1 = bar3(YSource); and press Enter.
You see a new bar chart. Even though the data is in graphic format, it’s still pretty boring. To make the bar chart easier to work with, the next step changes the y-axis labels.
3. Type CB1 = colorbar('EastOutside'); and press Enter.
You see a color bar appear on the right side of the plot, as shown in Figure 7-12. You can choose other places for the color bar, including inside the plot. For now, don’t worry about the color bar ticks not matching those of the bar chart.
4. Type the following code into the Command Window, pressing Enter after each line:
for Element = 1:length(Bar1)
ZData = get(Bar1(Element),'ZData');
set(Bar1(Element), 'CData', ZData,…
'FaceColor', 'interp')
end
FIGURE 7-12: The color bar appears on the right side of the plot.
A number of changes take place. The bars are now colored according to their value. In addition, the ticks on the color bar now match those of the bar chart, as shown in Figure 7-13. However, the color bar just contains numbers, so it doesn’t do anything more than the y-axis labels do to tell what the colors mean.
FIGURE 7-13: The bars are now colored to show their values.
5. Type set(CB1, 'YTickLabel', {'', 'Awful', 'OK', 'Better', 'Average', 'Great!', 'BEST'}); and press Enter.
The chart now has meanings assigned to each color level, as shown in Figure 7-14.
FIGURE 7-14: The color bar now conveys meaning to the bar chart.
The color scheme that MATLAB uses by default isn’t the only color scheme available. The colormap() function lets you change the colors. For example, if you type colormap('cool') and press Enter, the colors change appropriately. You can also create custom color maps using a variety of techniques. To get more information, see the colormap() documentation at https://www.mathworks.com/help/matlab/ref/colormap.html.
Interacting with daspect
How the 3D effect appears onscreen depends on the data aspect ratio. The daspect() function lets you obtain the current aspect ratio and set a new one. The aspect ratio is a measure of how the x-, y-, and z-axis interact. For example, an aspect ratio of [1, 2, 3] would mean that for every 1 unit of the x-axis, there are two units of the y-axis and three units of the z-axis. Perform the following steps to see how this feature works:
1. Type YSource = [1, 3, 5; 3, 7, 9; 5, 7, 11]; and press Enter.
MATLAB creates a data source for you.
2. Type Bar1 = bar3(YSource); and press Enter.
You see a 3D bar chart appear.
3. Type rotate(Bar1, [0, 0, 1], 270); and press Enter.
The bar chart rotates so that you can see the individual bars easier, as shown in Figure 7-15.
FIGURE 7-15: A 3D bar chart that you can use to work with the data aspect ratio.
4. Type daspect() and press Enter.
The output contains three values, like this:
ans =
0.3571 0.2679 2.1670
So, you now know the current aspect ratio of the plot, with the first number representing the x-axis value, the second number the y-axis value, and the third number the z-axis value. Your numbers may not precisely match those shown in the book.
5. Type daspect([.25, 1, 1.2]); and press Enter.
The data aspect ratio changes to create tall, skinny-looking bars like those shown in Figure 7-16. Compare Figures 7-15 and 7-16, and you see that the differences between the individual bars appears greater, even though nothing has changed. The data is precisely the same as before, as is the rotation, but the interpretation of the data changes.
FIGURE 7-16: Modifying the aspect ratio changes how the data is perceived.
6. Type daspect([.65, .5, 7]); and press Enter.
The impression is now that the differences between the data points are actually quite small. Again, nothing has changed in the data or the rotation. The only thing that has changed is how the data is presented.
7. Type daspect('auto') and press Enter.
The data aspect returns to its original state.
Interacting with pbaspect
The previous section tells how to modify the data aspect ratio. In addition, you see a number of examples that show how to use rotation to modify the appearance of the data. This section discusses the plot box aspect ratio. Instead of modifying the data, the plot box aspect ratio modifies the plot box — the element that holds the plot in its entirety — as a whole. The appearance of the data still changes, but in a different way than before. The following steps get you started with this example:
1. Type YSource = [1, 3, 5; 3, 7, 9; 5, 7, 11]; and press Enter.
MATLAB creates a data source for you.
2. Type Bar1 = bar3(YSource); and press Enter.
You see a 3D bar chart appear.
3. Type rotate(Bar1, [0, 0, 1], 270); and press Enter.
The bar chart rotates so that you can see the individual bars easier. (Refer to Figure 7-15.)
4. Type pbaspect() and press Enter.
As before, you get three values: x-, y-, and z-axis. However, the numbers differ from before because now you’re working with the plot box aspect ratio and not the data aspect ratio. Here are typical output values at this point:
ans =
1.1326 1.6180 1.0000
5. Type pbaspect([1.5, 1.5, 7]); and press Enter.
The differences between the data points seem immense, as shown in Figure 7-17.
Notice how changing the plot box aspect ratio affects both the plot box and the data so that the plot box no longer is able to change settings, such as the spacing between bars (as shown in Figures 7-15 and 7-16). This means that you don’t have to worry about bars ending up outside the plot area and not being displayed. The bars and the plot box are now locked together.
6. Type pbaspect([4, 5, 1]); and press Enter.
The data points now seem closer together, even though nothing has changed in the data. At this point, it helps to compare Figures 7-15 through 7-17. These figures give you a better idea of how aspect ratio affects the perception of your data in various ways.
7. Type pbaspect('auto'); and press Enter.
The plot aspect returns to its original state.
FIGURE 7-17: The data and plot box are locked together.