0% found this document useful (0 votes)
54 views

Basic Data Handling and Plotting With SCILAB: January 2013

Scilab

Uploaded by

Sabha Nayagham
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Basic Data Handling and Plotting With SCILAB: January 2013

Scilab

Uploaded by

Sabha Nayagham
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/321998542

Basic Data Handling and Plotting with SCILAB

Chapter · January 2013

CITATIONS READS

0 2,110

1 author:

Howard Njoku
University of Nigeria
33 PUBLICATIONS   74 CITATIONS   

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

Performance Evaluation of Models for Estimating Solar Radiation on Tilted Surfaces View project

Modelling of solar water heater in order to reduce the peak demand- Sunyani as a case study View project

All content following this page was uploaded by Howard Njoku on 22 December 2017.

The user has requested enhancement of the downloaded file.


MATLAB/SCILAB for Scientific & Engineering Systems Analysis, pp. 161–173, 2013
Copyright © H.O. NJOKU, 2013. All rights reserved

CHAPTER 11
BASIC DATA HANDLING AND PLOTTING WITH SCILAB
by

H.O. NJOKU
Department of Mechanical Engineering
University of Nigeria, Nsukka
[email protected]; +234 (0)809 148 9064

11.1 Data Handling with Scilab


11.1.1 Extracting data from external (.xls) files
It often happens that some work has been done using the Microsoft Excel software and further analy-
sis, which may include plotting, of the intermediate results needs to be carried out using Scilab. Scilab
offers some simple commands for importing data saved in the .xls format.
Let us create a .xls file called ‘Data.xls’ in a convenient location (the Desktop folder in this case,)
containing the data shown in Tables 1 on Sheet1.

• To read the contents of the Data.xls file, we use the command:

sheets = readxls(‘/home/sis_uche/Desktop/Data.xls’)

• To determine the file type, we use the command:

typeof(sheets)

161
162 NJOKU: Plotting with Scilab

Table 11.1: Data for Sheet1 of ‘Data.xls’


500 500 500 500 500 500 500 500 500 500 500
500 450 450 450 450 450 450 450 450 450 500
500 450 400 400 400 400 400 400 400 450 500
500 450 400 350 350 350 350 350 400 450 500
500 450 400 350 300 300 300 350 400 450 500
500 450 400 350 300 250 300 350 400 450 500
500 450 400 350 300 300 300 350 400 450 500
500 450 400 350 350 350 350 350 400 450 500
500 450 400 400 400 400 400 400 400 450 500
500 450 450 450 450 450 450 450 450 450 500
500 500 500 500 500 500 500 500 500 500 500

• To assign the contents of the 1st sheet to the variable ‘s1’, enter the command:

s1 = sheets(1)

• To get the numeric values stored in s1 and assign them to a variable ‘A’, enter the command:

A = s1.value

This command and the previous one can be carried out in one step as follows:

A = sheets(1).value

• The variable A holds a matrix on which any of the standard matrix operations can be performed.
To perform a math operation on matrix A:

B = 3 * A

• To perform another math operation on a subset of matrix A:

C = log(A(2:5,4:8))

11.1.2 Exporting data to external (.csv) files


There are also instances when data obtained with Scilab operations may be needed for further oper-
ations on other software. Such cases may arise when collaborating with colleagues who do not use
Scilab or when post processings can be more easily done with other software. It is easiest to export
such data to a .csv (comma separted value) file which can be read by numerous software, including
Microsoft Excel.
The Scilab command for doing this is the ‘write_csv’ command.
163 NJOKU: Plotting with Scilab

• Let us generate a 5 by 5 matrix holding some random data and assign it to the variable ‘D’:

D = rand(5,5)*15

• In order to write the data to disk as a .csv file, we use the write_csv command in any of the
forms listed below:
// create equal space (tab) seperated .csv file
2 write_csv(D,’/home/sis_uche/Desktop/Data.csv’,’\t’,’.’)

4 // create comma (’,’) seperated .csv file


write_csv(D,’/home/sis_uche/Desktop/Data.csv’,’,’,’.’)
6
// creat .csv file with comma decimal points
8 write_csv(D,’/home/sis_uche/Desktop/Data.csv’,’\t’,’,’)

11.2 2D Plots in Scilab


The results of our most complex analysis are best understood when presented as appealing and well
laid out graphical plots. Next, we explore some simple commands offered by Scilab for producing
high quality publication-ready plots.

11.2.1 Single line plots


We wish to plot the simple function
y = sin(2x + 1)
on the interval 0 to π. Entering the following lines of command in a scinotes page and executing will
result in the output shown in Fig. 11.1.
x = linspace(0,%pi,21);
2 y = sin(2*x + 1);
scf(1);
4 clf(1);
plot(x,y,’o-b’);
6 xlabel(’$0 \leq x \leq \pi$’,’fontsize’,4,’color’,’red’);
ylabel(’$ y(x)=sin(2*x+1)$’,’fontsize’,4,’color’,’red’);
8 title(’Trig. function (21 points)’,’color’,’red’,’fontsize’,4);
legend(’Trig. Function Evaluation’);

The command on line 1 generates a row matrix of 21 equally space elements having 0 (zero) and π as
the first and last elements, and assigns it to the variable x. The command on line 2 defines our simple
trigonometric function, performing an operation on x and assigning the result to y.
164 NJOKU: Plotting with Scilab

Figure 11.1: Simple line plot with latex annotations.

scf(1) and clf(1) on lines 3 and 4 mean ‘set current figure’ and ‘clear current figure’, respec-
tively. By these commands, we ensure that any plots on the current figure space (set equal to 1) is
cleared and the subsequent plot to be generated appears on this space. When no number is specified,
the clf() command clears all open figures, while the scf command sets the current figure to zero.
A plot of y against x is generated by the plot(x,y,‘o-b’) command on line 5.

11.2.2 Managing plot properties


Specifying line types, colours and markers

The basic command for single line plots in Scilab is plot(x,y). This will generate a black conti-
nous line with no markers. By including the optional argument ‘o-b’, we obtain the default solid
line (-), of blue colour (b) and with a circle line marker (o). Other options are specified as follows.

• Line types: Other line types can be specified with


‘-’ for solid line (which is the default), ‘- -’ for dashed line, ‘:’ for dotted line, and ‘-.’ for
dash-dotted line.

• Line colours: Other line colours can be specified with


165 NJOKU: Plotting with Scilab

Table 11.2: Annotation property keywords and options


keyword options
‘color’ any of the color options specified earlier
‘fontsize’ 0 for 8pts, 1 for 10pts, 2 for 12pts, 3 for 14pts, 4 for 18pts,
and 5 for 24pts
‘edgecolor’ any of the color options specified earlier
‘position’ a 2d vector [xvalue yvalue] that manually position the
annotation on the screen. xvalue and yvalue should be
between 0 and 1
Other properties like ‘backgroundcolor’, ‘fontname’, ‘rotation’, ‘visible’ may be
specified in the same command.

‘r’ for red, ’g‘ for green, ‘b’ for blue, ‘c’ for cyan, ‘m’ for magenta, ‘y’ for yellow, ‘k’ for black
(which is the default), and ‘w’ for white.
• Line markers: Other line markers can be specified with
‘+’ for plus sign, ‘o’ for circle, ‘*’ for asterisk, ‘.’ for point, ‘x’ for cross, ‘s’ or ‘square’
for square, ‘d’ or ‘diamond’ for diamond, ‘ˆ’ for upward pointing triangle, ‘v’ for downward
pointing triangle, ‘<’ for left pointing triangle, ‘>’ for right pointing triangle, ‘pentagram’ for
star, and ‘none’ for no marker (which is the default).

Including plot annotations

Axis labels: We use the commands ‘xlabel’, ‘ylabel’ (on lines 6 and 7, respectively), and
‘zlabel’ (in the case of 3-d plots) for adding labels to the x-, y- and z-axes of our plots.
Plot titles: The ‘title’ command is used to give a title to the plot.
Legends: The ‘legend’ command is used to display legend, especially when there are multiple lines
on a plot.
Annotation properties: The axis label, plot title and legend commands mentioned above require only
one compulsory arguement which is the quoted text we wish to appear as the axis label, plot title or
legend. However, the final appearance of the included text, such as its colour, fontsize, position, etc
can be easily modified using any of the keywords and options listed in Table 11.2, which must be
enclosed in quotes.

Axes and Grids

In order to modify the appearance of the axes of our plots, we first get the handle on current axes,
using the gca() command, viz.:
props = gca()
166 NJOKU: Plotting with Scilab

Thereafter, with

props.axis_properties = option

any of the axis properties can be modified. Try

props.x_location = ‘top’
props.data_bounds = [xmin, ymin; xmax, ymax]

Grid lines can be included at specified specified intervals with the command:

props.grid = [xinterval yinterval]

The next set of commands incorporates all that has been discussed so far, and the output is shown in
Fig. 11.2.
x = linspace(0,%pi,21);
2 y = sin(2*x + 1);
scf(1);
4 clf(1);
plot(x,y,’o-b’);
6 xlabel(’$0 \leq x \leq 3$’,’fontsize’,4,’color’,’red’);
ylabel(’$ y(x)=sin(2*x+1)$’,’fontsize’,4,’color’,’red’);
8 title(’Trig. function (21 points)’,’color’,’red’,’fontsize’,4,’position’,[0.75
-1.8]);
legend(’Trig. Function Evaluation’);
10 props = gca()
props.x_location = ’top’
12 props.data_bounds = [0, -1.5; 3, 1.5]
props.grid = [0.5 0.5]

11.2.3 Multiple Line Plots


A lot of the plots we will be dealing with in real life situations will be composed of more than a single
line. Inserting additional lines to our plots is as easy as including extra plot() commands. For

example, in order to add plots of the functions 0.5y and y to our initial plot, our commands will be
modified as shown in the next box to give the output shown in Fig. 11.3.
x = linspace(0,%pi,21);
2 y = sin(2*x +1);
scf(1);
4 clf(1);
plot(x,y,’o-b’);
6 plot(x,0.5*y,’^--k’);
167 NJOKU: Plotting with Scilab

Figure 11.2: Modified line plot with grid lines.

plot(x,sqrt(y),’*:g’);
8 xlabel(’$0 \leq x \leq \pi$’,’fontsize’,4,’color’,’red’);
ylabel(’$ y(x),\, 0.5 y,\, \sqrt{y}$’,’fontsize’,4,’color’,’red’);
10 title(’Function evaluation (21 points)’,’color’,’red’,’fontsize’,4);
legend(’$y(x)$’,’$0.5 y$’,’$\sqrt{y}$’);

We see that modifying the legend is also as straightforward as specifying appropriate text for each
additional line, thus:

legend(‘$y(x)$’,‘$0.5 y$’,‘$\sqrt{y}$’)

11.2.4 Plotting multiple plots on a single page


Including more than one plot in the same figure is done in Scilab with the subplot() command.
The syntax is as follows:

subplot(i,j,k)

where i is the number of plot rows, j, the number of plot columns, and k, the location of the current
plot, counting left-to-right from the first plot location. The use of the subplot() command is
explored in a later section.
168 NJOKU: Plotting with Scilab

Figure 11.3: Multiple line plot.

11.2.5 Plotting bar charts


Vertical bar charts

The command sequence for plotting vertical bar charts is simply:

bar(x,y[,width, color, style])

where x is a real scalar or vector of size N and y is a real scalar, vector of size N or a matrix of size
N * M. The value of the optional arguement width lies between 0 and 1, color may be specified
as earlier stated, and style may be either ‘grouped’ or ‘stacked’.
Let’s try out the following:
clf();
2 x = [31, 59, 90];
y = [2, 10, 12; 6, 4, 14; 8, -6, 16];
4 bar(x,y,0.6,’grouped’);
xtitle(’1st Quater Expenses’, ’Day number’, ’Amount (NGN)’);
6 legend(’Accomodation’, ’Gifts’, ’Feeding’, "in_lower_left");

The output is shown in Fig. 11.4


169 NJOKU: Plotting with Scilab

Figure 11.4: Vertical bar chart.

Horizontal bar charts

Instead of a vertical bar chart, our desire could instead be to create a horizontal bar chart. This will
be accomplished with the command:

barh(x,y[,width, color, style])

where all the command arguements are as earlier defined.


Let’s try the following:
clf();
2 y = [2, 10, 12; 6, 4, 14; 8, -6, 16];
barh(x,y,0.6,’grouped’);
4 xtitle(’1st Quater Expenses’, ’Amount (NGN)’, ’Month’);
legend(’Accomodation’, ’Gifts’, ’Feeding’, "in_lower_left");
6 a = gca();
a.y_ticks.labels = [’Jan’; ’Feb’; ’Mar’];

whose output is shown in Fig. 11.5. Note that the legend generated in the horizontal bar chart does
not convey much information. This reminds us that when using Scilab for creating plots you’ll have
to determine which kind of plot is most appropriate for the data you have. Note also that that an
a.y_ticks.labels command has been used to specify text tick labels on the y-axis. The same
can be done on the x-axis with an a.x_ticks.labels command.
170 NJOKU: Plotting with Scilab

Figure 11.5: Horizontal bar chart.

11.2.6 Plotting pie charts


The command sequence for plotting pie charts is as follows:

pie(x[,sp, txt])

where x is a scalar or vector of positive real numbers. The optional sp is a real scalar or vector of
real numbers while txt is a cell or vector of strings corresponding to the elements of x.
Let’s try the following:
clf();
2 x = [31, 1.1, 6, 5.2, 8, 4.5, 22];
pie(x,[1,0,0,0,1,1,1],[’Defence’, ’Science & Tech’,’Education’, ’Health’, ’
Culture’, ’Tourism’, ’Power and Steel’]);
4 title(’Sectoral Expenditure for 2018’,’color’,’red’,’fontsize’,4);

The output is shown in Fig. 11.6

11.3 3D Plots in Scilab


Next, we consider two types of 3 dimensional plots we can create with Scilab — contour plots and
surface plots.
171 NJOKU: Plotting with Scilab

Figure 11.6: Vertical bar chart.

11.3.1 Contour plots


To show how data that was saved in .xls format may be imported and used for creating plots in Scilab,
we will now import the Excel file data of Table 1 in section 1.1 and generate a contour plot with it:
sheets = readxls(’/home/sis_uche/Desktop/ScilabPlotsTraining/Data.xls’)
2 s1 = sheets(1);
A = s1.value;
4 clf();
lon = linspace(4,14,11);
6 lat = linspace(2,12,11);
contour(lon,lat,A,7);
8 xlabel(’Longitude’);
ylabel(’Latitude’);
10 title(’Variation of emision intensity with location.’);

By the command on line 1, we read the .xls file and assign it to the variable sheets. Next on line
2, we assign the first sheet to a variable (s1), and in the subsequent commands, perform the contour
plotting operations. The output is shown in Fig. 11.7.

11.3.2 3D surface plots


Of the numerous 3d surface plot commands available in Scilab, two simple ones are considered here –
the mesh and the surf commands. The mesh command generates surface meshes, while the surf
172 NJOKU: Plotting with Scilab

Figure 11.7: Vertical bar chart.


173 NJOKU: Plotting with Scilab

command generates coloured surfaces. The mesh and surf commands’ syntax is as follows:

mesh(x,y,z)
surf(x,y,z)

where x and y are two vectors whose dimensions (M and N, respectively) correspond to those of z,
which is a real M*N matrix which defines the surface height.
Let’s try out the following:
clf();
2 x = [0:0.3:2*%pi]’;
y = [0:0.3:2*%pi];
4 z = sin(x)*cos(y);
scf(0);
6 mesh(x,y,z);
scf(1);
8 surf(x,y,z);

The mesh command output is shown in Fig. 11.8(a), while the output of the surf command is shown
in Fig. 11.8(b).
Both plots can be jointly generated using the subplot command:
clf();
2 x = [0:0.3:2*%pi]’;
y = [0:0.3:2*%pi];
4 z = sin(x)*cos(y);
subplot(211);
6 mesh(x,y,z);
subplot(212);
8 surf(x,y,z);

to give the output of Fig. 11.9.

11.4 Conclusion
So very much more can be done with Scilab in terms of graph plotting which can be explored in the
Scilab help environment and numerous online resources. This brief discussion is aimed at arousing
interest in this direction.
174 NJOKU: Plotting with Scilab

(a) Mesh.

(b) Surf.

Figure 11.8: Scilab surface plots.


175 NJOKU: Plotting with Scilab

Figure 11.9: Scilab surface plots.

View publication stats

You might also like