1 >> Lecture 3
2 >>
3 >> -- Graphics
4 >>
Zheng-Liang Lu 119
Introduction
• Engineers use graphic techniques to make the information easier to understand.
• With graphs, it is easy to identify trends, pick out highs and lows, and isolate data points that may be measurement or calculation errors.
• Graphs can also be used as a quick check to determine if a computer solution is yielding expected results.
• A set of ordered pairs is used to identify points on a 2D graph.
Zheng-Liang Lu 120
2D Line Plot
• plot(x , y ) creates a 2D line plot for all (x , y ) pairs in order.
• You may use more parameters for the plot as follows:
Zheng-Liang Lu 121
Example
1 clear; clc; close all;
2
3 x = linspace(0, 2 * pi, 20);
4 y = sin(x);
5
6 figure; plot(x, y, "r-o");
7 grid on;
• Call figure to create a figure.
• Use close to close all figures or specific one.
• Use grid to add the gray grid as the background.
Zheng-Liang Lu 122
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
Zheng-Liang Lu 123
Example: Multiple Curves
1 clear; clc; close all;
2
3 x = linspace(0, 2 * pi, 50);
4 figure; hold on; grid on;
5 plot(x, sin(x), '*');
6 plot(x, cos(x), 'o');
7 plot(x, sin(x) + cos(x), '+');
• Use hold to put multiple curves in the same figure.
Zheng-Liang Lu 124
0 1 2 3 4 5 6 7 -1.5
-1 -0.5 0 0.5 1 1.5
Zheng-Liang Lu 125
Selected Annotations
• Use title to add a title to the plot.
• Use xlabel to add a label to the x axis of the plot.
• Use ylabel to add a label to the y axis of the plot.
• Use legend to add legends for lines.
• More annotations can be created by annotation.
1• Note that you can always generate the codes associated with the plot you modified.
1See https:
//www.mathworks.com/help/matlab/examples/annotating-plots.html.
Zheng-Liang Lu 126
Example
1 clear; clc; close all;
2
3 x = linspace(0, 2 * pi, 30);
4 y = sin(x); z = cos(x);
5
6 figure; hold on; grid on;
7 plot(x, y, "o--");
8 plot(x, z, "x:");
9 legend("Input", "Output", "location", "best");
10
11 xlabel("Time (s)"); ylabel("Amplitude (unit)");
12 title("Title");
13 annotation("textarrow", [.3, .6], [.7, .4] , ...
14 "String", "ABC");
Zheng-Liang Lu 127
0 1 2 3 4 5 6 7 Time (s)
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
Amplitude (unit)
Title
Input Output ABC
Zheng-Liang Lu 128
Graphics Objects
• You can use plot tool (in the figures) to change the properties.
• Graphics objects are the components for data visualization.
• Each object can be assigned to a unique identifier, called a graphics handle.
• Via graphics handles, you can manipulate their properties
2by the following instructions:
• set: set properties.
• get: query properties.
2See http:
//www.mathworks.com/help/matlab/graphics-object-properties.html.
Zheng-Liang Lu 129
Example
1 clear; clc; close all;
2
3 x = linspace(-1, 1, 100);
4 h = plot(x, sin(1 ./ x));
5 grid on;
6 set(h, "Marker", "o");
7 set(h, "MarkerSize", 5);
8 set(h, "LineWidth", 1.5);
9 set(h, "LineStyle", ":");
10 set(h, "MarkerEdgeColor", "r");
11 set(h, "MarkerFaceColor", "g");
Zheng-Liang Lu 130
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 -1
-0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
Zheng-Liang Lu 131
Graphics Object Identification
3• gcf: get current figure
• gca: get current axis
• gco: get current object
3See http://www.mathworks.com/help/matlab/creating_plots/
accessing-object-handles.html.
Zheng-Liang Lu 132
Output Figures
• You can save one figure as a specific image format.
• For example, bmp, jpeg, and eps.
• Use the hot key ctrl + s .
Zheng-Liang Lu 133
• You can also use print to save the figures.
41 clear; clc; close all;
2
3 x = linspace(0, 2 * pi, 20);
4 y = sin(x);
5
6 figure; plot(x, y, "r-o"); grid on;
7 print(gcf, "-djpeg", "sin.jpg", "-r300");
• Use saveas to save figure in a specific file format.
5• Use savefig to save figure and contents to fig-file.
64See http://www.mathworks.com/help/matlab/ref/print.html.
5See https://www.mathworks.com/help/matlab/ref/saveas.html.
6See https://www.mathworks.com/help/matlab/ref/savefig.html.
Zheng-Liang Lu 134
Exercise: TWSE:IND
1 clear; clc; close all;
2
3 [~, ~, raw] = xlsread("y9999.xlsx");
4 prices = [raw{4 : end, 2}];
5 dates = datetime(raw(4 : end, 1), ...
6 "format", "yyyy/MM/dd");
7
8 fig1 = figure;
9 plot(dates, prices); grid on;
10 ylabel("TWSE:IND");
11 annotation(fig1, "arrow", [0.4 0.88], [0.28 0.65]);
• Use datetime to convert a date string to a datetime object.
• Note that you need to specify a date format, say
"yyyy/MM/dd"
.
Zheng-Liang Lu 135
2008 2010 2012 2014 2016 2018 2020 4000
5000 6000 7000 8000 9000 10000 11000 12000 13000
TWSE:IND
Zheng-Liang Lu 136
Bar Plot
7• Use bar to draws a bar chart, for example,
1 clear; clc; close all;
2
3 x = randi(100, 8, 3);
4 bar(x); grid on;
• Try barh.
7See http://www.mathworks.com/help/matlab/ref/bar.html and http://www.mathworks.com/help/matlab/creating_plots/
overlay-bar-graphs.html.
Zheng-Liang Lu 137
1 2 3 4 5 6 7 8 0
10 20 30 40 50 60 70 80 90 100
Zheng-Liang Lu 138
Exercise: Traded Volumes of TWSE:IND
1 clear; clc; close all;
2
3 [~, ~, raw] = xlsread("y9999.xlsx");
4 volumes = [raw{4 : end, 3}];
5 dates = datetime(raw(4 : end, 1), ...
6 "format", "yyyy/MM/dd");
7
8 figure;
9 bar(dates, volumes); grid on;
10 ylabel("Traded volume");
Zheng-Liang Lu 139
1975 1980 1985 1990 1995 2000 2005 2010 2015 0
0.5 1 1.5 2 2.5 3 3.5
Traded volume
108
Zheng-Liang Lu 140
Dual y-Axes Plot
• Use yyaxis to specify the left/right y axis, for example,
1 clear; clc; close all;
2
3 x = linspace(0, 30, 300);
4 y1 = 10 * exp(-0.05 * x) .* sin(x);
5 y2 = 0.8 * exp(-0.5 * x) .* sin(10 * x);
6
7 figure;
8 yyaxis left;
9 plot(x, y1); grid on;
10 yyaxis right;
11 plot(x, y2);
• Use plotyy in old version.
Zheng-Liang Lu 141
0 5 10 15 20 25 30 -8
-6 -4 -2 0 2 4 6 8 10
-0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8
Zheng-Liang Lu 142
Exercise: Index feat. Volume in One Figure
1 clear; clc; close all;
2
3 [~, ~, raw] = xlsread("y9999.xlsx");
4 prices = [raw{4 : end, 2}];
5 volumes = [raw{4 : end, 3}];
6 dates = datetime(raw(4 : end, 1), ...
7 "format", "yyyy/MM/dd");
8
9 yyaxis left; plot(dates, prices);
10 ylabel("TWSE:IND"); grid on;
11 yyaxis right; bar(dates, volumes);
12 ylabel("Traded volume"); grid on;
Zheng-Liang Lu 143
1975 1980 1985 1990 1995 2000 2005 2010 2015 0
2000 4000 6000 8000 10000 12000 14000
TWSE:IND
0 0.5 1 1.5 2 2.5 3 3.5
Traded volume
108
Zheng-Liang Lu 144
Histogram Plot
9• Histograms group the numeric data into bins.
• Use histogram to create histogram plots.
81 clear; clc; close all;
2
3 data = randn(1, 1e3) .ˆ 2;
4 figure;
5 histogram(data, ...
6 "BinMethod", "integers", ...
7 "Normalization", "probability");
8 grid on;
8If your version is before 2014, use hist.
9More details could be found in https://www.mathworks.com/help/
matlab/ref/matlab.graphics.chart.primitive.histogram.html.
Zheng-Liang Lu 145
0 2 4 6 8 10 0
0.1 0.2 0.3 0.4 0.5 0.6
Zheng-Liang Lu 146
Exercise: Distribution of Return Rates of TWSE:IND
1 clear; clc; close all;
2
3 [~, ~, raw] = xlsread("y9999.xlsx");
4 prices = [raw{4 : end, 2}];
5 dates = datetime(raw(4 : end, 1), ...
6 "format", "yyyy/MM/dd");
7 return rates = diff(prices) ./ prices(1 : end - 1);
8
9 figure;
10 histogram(return rates * 100, ...
11 "binmethod", "integer", ...
12 "normalization", "probability");
13 xlabel("Return rate (%)");
14 ylabel("Probability"); grid on;
Zheng-Liang Lu 147
-8 -6 -4 -2 0 2 4 6 8 Return rate (%)
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5
Probability
Zheng-Liang Lu 148
Grid Plot: subplot
101975 1980 1985 1990 1995 2000 2005 2010 2015 0
5000 10000 15000
TWSE:IND
1975 1980 1985 1990 1995 2000 2005 2010 2015 0
1 2 3 4
Traded volume
108
10See https://www.mathworks.com/help/matlab/ref/subplot.html.
Zheng-Liang Lu 149
1 clear; clc; close all;
2
3 [~, ~, raw] = xlsread("y9999.xlsx");
4 prices = [raw{4 : end, 2}];
5 volumes = [raw{4 : end, 3}];
6 dates = datetime(raw(4 : end, 1), ...
7 "format", "yyyy/MM/dd");
8
9 figure;
10 subplot(2, 1, 1); plot(dates, prices); grid on;
11 ylabel("TWSE:IND");
12 subplot(2, 1, 2); bar(dates, volumes, "r"); grid on;
13 ylabel("Traded volume");
• Use subplot(m, n, p) to divide the current figure into an m-by-n grid and use p to specify the certain subplot.
Zheng-Liang Lu 150
Digression: Table
11• Use table to create a table for column-oriented or tabular data that is often stored as columns in a spreadsheet.
• Use detectImportOptions to create import options based on the contents of a file (if readtable cannot read files correctly).
• Use stackedplot to draw a stacked plot of several variables with common x-axis.
11See https://www.mathworks.com/help/matlab/tables.html.
Zheng-Liang Lu 151
1 clear; clc; close all;
2
3 filename = "2330.csv";
4 s2330 = readtable(filename);
5 % Delete the first two rows.
6 s2330(1 : 2, :) = [];
7 % Assign the header name for each column.
8 s2330.Properties.VariableNames = ["Date", "Open", ...
"High", "Low", "Close", "Volume"];
9 % Convert date strings to datetime objects.
10 s2330.Date = datetime(s2330.Date, ...
11 "format", "yyyy-MM-dd");
12 % Use stackedplot to draw an interactive plot!
13 stackedplot(s2330, {"Close", "Volume"}, ...
14 "xvar", "Date"); grid on;
Zheng-Liang Lu 152
200 250 300
Close
Jul 2017 Jan 2018 Jul 2018 Jan 2019 Jul 2019 Date
2 4 6 8 10 12 14
Volume 104
Zheng-Liang Lu 153
Selected Table Functions
• File I/O: readtable, writetable.
• Summary information: head, tail, summary, stackedplot.
• Sort, rearrange, and customize: sortrows, unique, addvars, removevars, rows2vars, stack, unstack, inner2outer.
• Join and set operations: join, innerjoin, outerjoin, union, intersect, ismember, setdiff, setxor.
• Apply functions to table contents: varfun, rowfun, findgroups, splitapply, groupsummary
Zheng-Liang Lu 154
Exercise: Merging Two Tables
1 clear; clc; close all;
2
3 gspc = readtable("ˆGSPC.csv");
4 twii = readtable("ˆTWII.csv");
5 % Merge two time series by union of dates.
6 merged table = outerjoin(twii, gspc, ...
7 "Keys", "Date", ...
8 "MergeKeys", 1);
9 stackedplot(merged table, ...
10 {"Close twii", "Close gspc"}, ...
11 "xvariable", "Date"); grid on;
Zheng-Liang Lu 155
8000 9000 10000 11000
Close_twii
Jan 2015 Jan 2016 Jan 2017 Jan 2018 Jan 2019
Date 2000
2200 2400 2600 2800
Close_gspc
Zheng-Liang Lu 156
Candle Chart with Timetable
121 % Ingore the part identical to the previous ...
example of 2330.
2
3 s2330 = table2timetable(s2330, "RowTimes", "Date");
4 candle(s2330(end - 30 : end, :)); % last 30 days
5 ylabel("Daily price (TWD)");
• Use timetable to convert the table (with variable names:
"Open"
,
"High",
"Low",
"Close") to a timetable by specifying the RowTimes.
• Try priceandvol.
12See https://www.mathworks.com/help/finance/candle.html and https://www.mathworks.com/help/matlab/timetables.html with https://www.mathworks.com/help/finance/examples/
using-timetables-in-finance.html.
Zheng-Liang Lu 157
Nov 01 Nov 08 Nov 15 Nov 22 Nov 29 Dec 06 Dec 13 Dec 20 Dec 27 2019 300
305 310 315 320 325 330 335 340 345
Daily price (TWD)
Zheng-Liang Lu 158
Smart Plot: fplot
• Use fplot to make a line plot over a specific range with adaptive steps.
• You may assign a function in a string form to fplot.
131 clear; clc; close all;
2
3 fplot("sin(1 / x)", [-0.05, 0.05]); grid on;
13Warning: fplot will not accept character vector or string inputs in a future release.
Zheng-Liang Lu 159
-0.05 -0.04 -0.03 -0.02 -0.01 0 0.01 0.02 0.03 0.04 0.05 -1
-0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
Zheng-Liang Lu 160
errorbar
141 clear; clc; close all;
2
3 x = 0 : 10 : 100;
4 y = [20 30 45 40 60 65 80 75 95 90];
5 yneg = [1 3 5 3 5 3 6 4 3 3];
6 ypos = [2 5 3 5 2 5 2 2 5 5];
7 xneg = [1 3 5 3 5 3 6 4 3 3];
8 xpos = [2 5 3 5 2 5 2 2 5 5];
9 errorbar(x, y, yneg, ypos, xneg, xpos, "o");
10 grid on;
14See https://www.mathworks.com/help/matlab/ref/errorbar.html.
Zheng-Liang Lu 161
0 10 20 30 40 50 60 70 80 90 100 10
20 30 40 50 60 70 80 90 100
Zheng-Liang Lu 162
Pie Chart
26%
19%
21%
13%
21%
Zheng-Liang Lu 163
1 clear; clc; close all;
2
3 X = rand(1, 5);
4 labels = {"A", "B", "C", "D", "E"};
5 explode = [0, 1, 0, 1, 0];
6 pie(X, explode, labels);
• Use pie to create a pie chart.
15• Note that the explode vector is used to offset slices for the nonzero elements.
15See https://www.mathworks.com/help/matlab/ref/pie.html.
Zheng-Liang Lu 164
Word Cloud
market_values
Zheng-Liang Lu 165
1 clear; clc; close all;
2
3 [~, ~, raw] = xlsread("twse mktValue.xlsx");
4
5 stock ticks = string(raw(4 : end, 1));
6 idx = strcmp(raw(:, 3), "-"); % Find all "-"s.
7 raw(idx, 3) = {0}; % Replace them by 0.
8 market values = [raw{4 : end, 3}]';
9
10 tbl = table(stock ticks, market values);
11 figure;
12 wordcloud(tbl, "stock ticks", "market values");
• Use strcmp to compare strings and return a boolean vector.
• Use wordcloud to create a word cloud chart from text data.
1616See https://www.mathworks.com/help/matlab/ref/wordcloud.html.
Zheng-Liang Lu 166
Contours
17• Use meshgrid to partition the specified range of x and y .
• Note that the return values are in form of matrices. (Why?)
1 clear; clc; close all;
2
3 x = linspace(-2 * pi, 2 * pi);
4 y = linspace(0, 4 * pi);
5 [X, Y] = meshgrid(x, y);
6 Z = sin(X) + cos(Y); % Using vectorization.
7 figure; contour(X, Y, Z, "showtext", "on");
17See https://www.mathworks.com/help/matlab/ref/contour.html.
You may try contourf.
Zheng-Liang Lu 167
-1.5 -1.5
-1.5 -1.5
-1
-1
-1
-1
-1 -1
-1 -1
-0.5 -0.5 -0.5
-0.5 -0.5 -0.5
-0.5
-0.5 -0.5
-0.5
0 0
0
0
0
0 0
0 0
0
0
0 0
0.5 0.5
0.5 0.5
0.5
0.5 0.5
0.5 0.5
1 1
1 1
1
1
1
1
1.5 1.5
1.5 1.5
1.5 1.5
-6 -4 -2 0 2 4 6
0 2 4 6 8 10 12
Zheng-Liang Lu 168
Quiver (Velocity) Plot
• Use quiver(x , y , u, v ) to plot a vector (u, v ) at the coordinate (x , y ).
• Use peaks with a positive number as sample size to generate a set of 3d points.
181 clear; clc; close all;
2
3 [x, y, z] = peaks(20);
4 [u, v] = gradient(z);
5 figure; hold on; grid on;
6 contour(x, y, z, 10);
7 quiver(x, y, u, v);
18See https://www.mathworks.com/help/matlab/ref/peaks.html.
Zheng-Liang Lu 169
-3 -2 -1 0 1 2 3 -3
-2 -1 0 1 2 3
Zheng-Liang Lu 170
Mesh Plot
• Use mesh to draw a wireframe mesh.
1 clear; clc; close all;
2
3 x = linspace(-3, 3, 50);
4 y = x + pi / 2;
5 [X, Y] = meshgrid(x, y);
6 Z = cos(X) .* sin(Y);
7 figure; mesh(X, Y, Z); grid on;
8 xlabel("x"); ylabel("y"); zlabel("z");
Zheng-Liang Lu 171
-1 6 -0.5
4 4
z 0
2 0.5
y 2
x 1
0 0
-2 -2 -4
Zheng-Liang Lu 172
Surface Plot
• Use surf to draw a colored surface.
• Try meshz, meshc, surfc, and waterfall.
1 clear; clc; close all;
2
3 x = linspace(-2, 2, 25);
4 y = linspace(-2, 2, 25);
5 [X, Y] = meshgrid(x, y); % form all x-y pairs
6 Z = X .* exp(-X .ˆ 2 - Y .ˆ 2);
7 surf(X, Y, Z);
8 xlabel("x"); ylabel("y"); zlabel("z");
Zheng-Liang Lu 173
-0.5 2
1 2
z 0
1
y 0
x 0.5
-1 0
-1 -2 -2
Zheng-Liang Lu 174
Exercise
• Write a program to draw a surface plot for sinc(R) =
sin(R)R.
• Note that there exists a singularity at R = 0, which should be removed by replacing a zero with eps = 2.2204 × 10
−16.
1 clear; clc; close all;
2
3 [X, Y] = meshgrid(linspace(-10, 10, 51));
4 R = sqrt(X .ˆ 2 + Y .ˆ 2);
5 R(R == 0) = eps; % Avoid the singularity.
6 Z = sin(R) ./ R;
7 surf(X, Y, Z);
Zheng-Liang Lu 175
-0.5 10 0
5 10
0.5
0 5 1
-5 0
-5 -10 -10
Zheng-Liang Lu 176
3D Line Plot
• Use plot3 to draw a 3d curve.
1 clear; clc; close all;
2
3 t = linspace(0, 10 * pi, 100);
4 x = t .* sin(t); y = t .* cos(t);
5
6 figure;
7 plot3(x, y, t); hold on;
8 plot3(x, y, -t, "r");
9 axis equal; grid on;
Zheng-Liang Lu 177
-30 -20 -10
20 0
20 10
20
0 0
30
-20 -20
Zheng-Liang Lu 178
Misc
21• Use the button Rotate 3D to change the view angle.
• Use view to set the view angle.
19• Try colorbar and colormap.
201 clear; clc; close all;
2
3 peaks;
4 view([117, 58]); % View angle in degree.
5 colorbar; % Appends a colorbar to the current axes.
6 colormap summer; % Change the colormap.
19az: azimuth (horizontal) rotation; el: vertical elevation.
20See https://www.mathworks.com/help/matlab/ref/colormap.html.
21See
https://www.mathworks.com/products/matlab/plot-gallery.html.
Zheng-Liang Lu 179
-3 -2 -1
x -3 0
-2 -5
-1 1
y
0 1 2
2 3 3
Peaks
0 5
-6 -4 -2 0 2 4 6 8
Zheng-Liang Lu 180