Session 8: Plotting Graphs [June 7, 2011, 2:47 a.m.]
Objectives
In this session you will learn the following:
- Plotting 2 dimensional line graphs
- Annotating graphs with grids, axis labels, graph titles
- Exporting graphs for inclusion in documents
- Plotting 3 dimensional surface graphs
- Plotting multiple graphs on one page (subplot())
Functions for Plotting
In this session, we will learn the following functions:
plot(), plot2d(), xgrid(), xtitle(), legend(), plot3d(), linspace()
Plotting Basics
Scilab is a data plotter, that is, it plots graphs from the data you input. This is in contrast to function plotting programs (such as gnuplot) which plot graphs of functions without the user having to first explicitly generate the data required to plot the graph. Function plotting programs will decide the range of the values of independent variable and its data interval, generate the data on the fly and plot the graph.
Let us plot a graph of sin(x) and cos(x) over the range x = 0 to 2 pi. We will first create vector x, containing the values of the independent variable x. Then we will create the matrix y, containing the same number of rows as x, with values of sin(x) in its first column and values of cos(x) in its second column.
-->x = [0:%pi/16:2*%pi]';
-->y = [sin(x), cos(x)];
-->plot(x, y); xgrid(1); xtitle('Harmonic Functions', 'x', 'sin(x) and cos(x)');
This must result in the following graph being plotted:
Let me explain how this was achieved:
- Using the plot() function, we told Scilab to look for values of x in the first variable (namely x) and look for values of y in the second variable (namely y). The number of rows in x and y must be the same. Since y contains two columns, Scilab understands that it must plot two lines in the graph, one each for each column of values.
- Using xgrid() function, we told Scilab to plot grids parallel to the x- and y-axes in black color (argument 1 to the function xgrid()).
- Using the xtitle() function, we defined the title of the graph (first argument), title for the x-axis (second argument) and title for the y-axis (third argument).
In the same way, we could define a legend with the legend() function as follows:
-->plot(x, y); xgrid(1); xtitle('Harmonic Functions', 'x', 'sin(x), cos(x)'); legend(['sin(x)', 'cos(x)'], 3)
First argument to legend() is an array of strings containing the legend text and the second argument specifies the position. Use the online help to learn more about the legend() function.