Plotting Graphs - MATLAB Documentation
Plotting Graphs - MATLAB Documentation
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
Plotting graphs
Plotting graphs is a very common tool for illustrating results in science. MATLAB has many commmands that can be used for creating various kinds of plots.
Easy plots
The simplest buit-in function for plotting an explicit function is ezplot command. For example, we want to plot a parabola on the interval [-1,1]
The first input of ezplot command is a string describing the function. The second input (which is optional) is the interval of interest in the graph. Note that the function description is not necessarily a function in x variable. We can use any variable we like:
>> ezplot('sin(b)',[-2 3])
In this case, if we assign a value 2 to a variable first, says y=2, when executing:
>> y = 2; >> ezplot('x^2+y')
MATLAB will interpret y as a variable (not a value of 2). Hence, it will create a contour plot of the function
Another related command is fplot. It is used to plot a function with the form specified limits.
between
Plot command
1 of 10
4/13/2014 2:22 AM
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
The plot command is used to create a two-dimensional plot. The simplest form of the command is:
plot(x,y)
where x and y are each a vector. Both vector must have the same number of elements. For example:
>> x = 0:0.1:5; >> y = exp(-x); >> plot(x,y)
Once the plot command is executed, the figure Window opens and the plot is displayed The plot appears on the screen in blue which is the default line color. The plot command has additional arguments that can be used to specify the color and style of the line and the color and type of markers, if any are desired. With these options the command has the form:
plot(x,y,'linespec','PropertyName',PropertyValue)
Specifier
-
The line color specifiers are: Line Color red green blue cyan magenta yellow black white Specifier
r g b c m y k w
The marker type specifiers are: Marker Type plus sign circle asterisk point Specifier
+ o * .
2 of 10
4/13/2014 2:22 AM
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
Marker Type cross triangle (pointed up) triangle (pointed down) square diamond five-pointed star sixed-pointed star triangle (pointed left) triangle (pointed right)
Specifier
x ^ v s d p h < >
The specifiers are typed inside the plot command as strings. Within the string, the specifiers can be typed in any order and the specifiers are optional. For example:
>> x = 0:5; y = 2.^x; plot(x,y,'-or')
This command creates a plot with solid red line and the marker is a circle.
Description the width of the line (default 0.5, possible values are 1,2,3,...) the size of the marker (e.g., 5,6,... ) the color of the edge line for filled marker (e.g., r, b) the color of the filling for filled markers (e.g, r , b)
creates a plot with a blue dashed line and squares as markers. The linewidth is 2 points and the size of the square markers is 8 points. The marker has green filling.
Formatting a plot
Plots can be formatted by using MATLAB command that follow the plot or fplot commands, or interactively by using the plot editor in the Figure Window. Here we will explain the the first method which is more useful since a formatted plot can be created automatically every time the program is executed.
3 of 10
4/13/2014 2:22 AM
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
and:
>> ylabel('text as string')
The text command places the text in the figure such that the first character is positioned at the point with the coordinates x,y (according to the axes of the figure). The gtext command places the text at a position specified by the user (with the mouse).
Some of the PropertyName are: Property Name Rotation FontSize Description the orientation of the text (in degree) the size of the font (in points)
4 of 10
4/13/2014 2:22 AM
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
Property Name FontWeight Color Description the weight of the characters (light, normal, bold) the color of the text (e.g., r , b, etc.)
Some formatting can also be done by adding modifiers inside the string. For example, adding \bf, \it, or \rm, will create a text in bold font, italic style, and with normal font, rexpectively. A single character can be displayed as a subscript or a superscript by typing _ (the underscore character) or ^ in front of the character, respectively. A long superscript or subscript can be typed inside { } following the _ or the
^. For example: >> title('\bf The values of X_{ij}', 'FontSize',18)
Greek characters
Greek characters can be included in the text by typing \ (back slash) before the name of the letter. Character Letter
\alpha \beta \gamma \theta \pi \sigma
Description sets the limits of both x and y sets the same scale for both axes sets the axes region to be square sets the axis limits to the range of the data
grid on adds grid lines to the plot. grid off removes grid lines
5 of 10
4/13/2014 2:22 AM
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
creates 3 graphs: y vs x, v vs u, and t vs s , all in the same plot. The vector of each pair must have the same length. MATLAB automatically plots the graphs in different colors so that they can be identified. It is also possible to add line specifiers following each pair. For example:
>> plot(x,y,'-bo',u,v,'--rx',s,t,'g:s')
plots y vs x with a solid blue line and circles, v vs u with a dashed red lines with cross signs, t vs s with a dotted green line and square markers. For example, we plot the function first derivative for these graphs can be written as:
>> >> >> >> >> >> >> x = linspace(-2,4,20); y = 3*x.^3-26*x+10; dy = 9*x.^2-26; ddy = 18*x; ddy = 18*x; plot(x,y,x,dy,x,ddy); legend('y','first derivative','second derivative');
, and its ,
and second derivatives , all in the same plot. A script file that creates
The default colors of multiple graphs in MATLAB start from blue, red, and green, respectively.
Logarithmic Scales
The semilogy function plots x data on linear axes and y data on logarithmic axes. The semilogx function plots x data on logarithmic axes and y data on linear axes. The loglog function plots both x and y data
6 of 10
4/13/2014 2:22 AM
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
on logarithmic axes. For example, notice the difference between the two commands:
>> >> >> >> x = logspace(0,3,100); y = x.^2; semilogy(x,y) loglog(x,y)
(The logspace creates a vector of 100 elements in log scale with the first element 10^0 and the last element 10^(3).)
Polar plots
The polar command is used to plot functions in polar coordinates. The command has the form:
>> polor(theta,radius,'linespec')
where theta and radius are vectors whose elements define the coordinates of the points to be plotted. The line specifiers are the same as in the plot command. To plot a function domain, a vector for values of calculation. For example, a plot of the function with the corresponding values of in a certain is created first, and then a vector is created using element-wise
is done by:
>> theta = linspace(0,2*pi,200); >> r = 3*cos(theta/2).^2+theta; >> polar(theta,r)
The command divides the Figure Window into mxn rectangular subplots where plots will be created. The subplots are arranged like elements in a mxn matrix where each element is a subplot. The subplots are numbered from 1 through mn. The number increases from left to right within a row, from the first row to the last. The command
subplot(m,n,p) makes the subplot p current. This means that the next
plot command will create a plot in this subplot. For example, we create a plot that has 2 rows and 2 columns:
>> >> >> >> subplot(2,2,1);ezplot('sin(x)'); subplot(2,2,2);ezplot('exp(-x)'); subplot(2,2,3);ezplot('x^2'); subplot(2,2,4);ezplot('sin(x)/x');
7 of 10
4/13/2014 2:22 AM
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
When the plot or any other commands that generates a plot is executed, the Figure Window opens and displays the plot. If a Figure Window is already open and the plot command is executed, a new plot will replace the existing plot. It is also possible to open additional Figure Window. This is done by typing the command figure. Every time the command figure is entered, MATLAB opens a new Figure Window and after than we can enter the plot command to generate a plot in the last active Figure Window. The figure command can also have an input argument that is an integer figure(n) . The number corresponds to the number of a corresponding Figure Window. Figure Windows can be closed with the
close command. Several forms of the commmand are: close closes the active Figure Window close(n) closes the nth Figure Window close all closes all Figure Windows that are open
3. Stairs plots
Function format: stairs(x,y):
>> k=1:5;pmf = [1/4 1/4 1/4 1/8 1/8]; >> cdf =cumsum(pmf); >> stairs(k,cdf);
4. Stem plots
Function format: stem(x,y):
>> k=-5:5; Rk = 0.5.^abs(k); >> stem(k,Rk);
5. Pie plots
Function format: pie(x) :
>> grade=[11 18 26 9 5]; >> pie(grade)
6. Histograms
8 of 10
4/13/2014 2:22 AM
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
Histograms are plots that show the distribution of data. The overall range of a given set of data points is divided to smaller subranges (bins), and the histogram shows how many data points are in each bin. The height of the bar corresponds to the number of data points in the bin. The simplest form of the command is:
>> hist(y,M)
where y is a vector with the data points, and M is the number of bins. For example, we generate 10000 random numbers according to Gaussian distribution. Its histogram should look like a bell curve (due to the density function). This is done by typing:
>> y = randn(10000,1); >> hist(y,100)
term in
3-D plots
Surface, mesh, and contour plots are convenient ways to represent data that is a function of two independent variables, says . To plot data, a user must create three equal-sized arrays x,y, and z. The vector x and y contain the x values and the y values, and the vector z contains the function values associated with every point of x and y. MATLAB function meshgrid makes it easy to create the vector x,y arrays required for these plots. Then we evaluate the function values to plot at each of those (x,y) locations. Finally we call function mesh,surf or
contour to create the plot. For example, we plot the 2-dimensional Gaussian density function
Exercises
1. Write a MATLAB script to plot circular marker. 2. Write a MATLAB script to plot the magnitude of where versus from 0 to in steps of . The points should be connected by a 2-pt red line and each point should be marked with a 6-pt wide blue
for
to 3. The position
in log scale with 200 points. Plot the graph in log scale for both x and y axes. as a function of time of a particle that moves along a straight line is given by
Use subplot command to make the three plots of position, velocity, and acceleration on the same page. 4. Generate 10000 random numbers according to a uniform distribution on the interval [-5,5]. Plot the histogram of the data and discuss the result.
9 of 10
4/13/2014 2:22 AM
http://jitkomut.lecturer.eng.chula.ac.th/matlab/graphic.html
10 of 10
4/13/2014 2:22 AM