That is the fourth article in an occasional sequence of articles about Octave, a free open-source numerical programming atmosphere that’s largely appropriate with MATLAB. This sequence started with the article Octave: An Different to the Excessive Value of MATLAB. This text discusses plotting and graphics in Octave. Octave has intensive plotting and graphics options together with two-dimensional plots, histograms, three dimensional plots, and a variety of specialised plots and charts akin to pie charts. This text offers an outline of the important thing plotting and graphics options of Octave, discusses just a few gotchas, and provides a number of illustrative examples.
Octave can plot features and knowledge utilizing the built-in plot functio. For instance thiese options, this text makes use of knowledge on the value of gasoline in america from america Power Info Administration, a part of the US Division of Power. The info is taken from the Motor Gasoline Retail Costs, U.S. Metropolis Common report launched March 29, 2011. This knowledge is at present obtainable in Adobe Acrobat PDF file format, a comma separated worth (CSV) ASCII textual content format, and Microsoft Excel (XLS) spreadsheet format. The info from the CSV report was imported into Microsoft Excel, exported as an ASCII tab delimited textual content fiel after which lower and pasted into two tab-delimited ASCII recordsdata. The EIA fuel value report comprises a number of time sequence in a single file (leaded fuel costs, unleaded fuel costs, and several other extra). The leaded and unleaded fuel costs had been extracted manually within the Notepad++ textual content editor. These dataq recordsdata had been named: leaded.txt and unleaded.txt.
unleaded = dlmread('unleaded.txt');
The plot of unleaded gasonline costs above was generated utilizing the next Octave code:
unleaded = dlmread('unleaded.txt'); unleaded_rawtime = unleaded(:,2); unleaded_rawprice = unleaded(:,3); unleaded_good_index = discover(unleaded_rawprice < 10); unleaded_time_x = unleaded_rawtime(unleaded_good_index); unleaded_price = unleaded_rawprice(unleaded_good_index); unleaded_time = repair(unleaded_time_x/100) + rem(unleaded_time_x,100)*(1./12.); plot(unleaded_time, unleaded_price); title('Unleaded Common Gasoline Worth'); xlabel('Yr'); ylabel('US {Dollars} Per Gallon'); print('unleaded.jpg');
A couple of feedback could also be useful. dlmread is an Octave perform that reads ASCII knowledge recordsdata. It’s pretty versatile and might typically routinely establish the separator utilized in ASCII knowledge recordsdata such because the tab or a comma. If crucial, the consumer can explicitly specify the separator and different parameters of the information file. Nonetheless it’s common to come across knowledge recordsdata with numerous quirks. For instance, the EIA fuel value report comprises a number of time sequence in a single file. There are numerous months for which both knowledge is just not obtainable or not reported; these are indicated by a price of 10000000 for the fuel value. The code above makes use of the Octave discover perform to pick out the legitimate knowledge. Additional the yr and month are mixed in the format YYYYMM sso January 1970 could be “197001”, February 1970 is “197002”, and so forth. Used immediately within the Octave plot perform, this can produce a nonsense plot that isn’t helpful.. Thus, the instance code above makes use of Octave repair and mod features to compute a time in years (month numbers are transformed to fractions of a calendar yr). Octave has quite a few superior features akin to discover , repair, rem, and so forth that can be utilized to wash up and reformat knowledge as wanted.
The Octave perform plot handles the really plotting of the graph. The Octae plot perform is a really versatile plotting perform for 2 dimensional knowledge akin to time sequence. Each the Octave consumer guide and the construct in assist (assist plot) present detailed data on using plot.
Octave has in-built help for histograms. A histogram is a method of displaying the frequency of incidence of knowledge or occasions. One would possibly, for instance, be occupied with how typically fuel costs change by one %, two %, or ten % in a single month.
By default, the Octave hist perform creates a histogram with ten bins, which is usually not very helpful. One can specify extra bins simply.
Likelihood density features are normalized ito unity(1.0). With Octave one can simply generate histograms normalized to 1.0.
Now the values within the histogram of % modifications in fuel costs are normalized to 1.0. The histogram is an estimate of the likelihood density perform for fuel value modifications. One would possibly ponder whether this distribution is the Gaussian likelihood denisty, also referred to as the Regular or Bell Curve distribution. In reality, the histogram appears narrower than a typical Gaussian and in addition has some outliers, an extended tail, which aren’t typical of a real Gaussian distribution. The subsequent two figures present the Gaussian likelihood density perform and a histogram of artificial knowledge generated with Gaussian statistics utilizing the identical imply and variance because the precise fuel value knowledge.
It’s straightforward to see that the Gaussian, or Nornal or Bell Curve, distribution differs from the distribution of the fuel value knowledge. The precise knowledge has a narrower, sharper peak and lengthy tails. Now and again, fuel costs leap shaprly. It is a sample seen in lots of monetary and different kinds of belongings . Many common monetary fashions such because the Black-Scholes choice piricing mannequin assume Gaussian or near-Gaussian distributions which typically understates the dangers when a fniancial asset or commodity has lengthy non-Gaussian tails as gasoline does.
The histograms and associated plots above had been generated utilizing the next Octave code:
change = conv(unleaded_price, [-1 1]); len = size(unleaded_price); returns = change(2:len) ./ unleaded_price(2:len); returns = 100.0 * returns; % convert to % plot(unleaded_time(2:len), returns, 'g;return;'); title('Returns on Gasoline'); xlabel('Yr'); ylabel('Return (%)'); print('gas_returns.jpg'); printf('making plot 2n'); fflush(stdout); determine(2) hist(returns); title('hist(returns)'); print('hist_returns.jpg'); xlabel('Return (%)'); ylabel('Counts'); printf('making plot 3n'); fflush(stdout); determine(3) hist(returns, 100); title('hist(returns, 100) (100 BINS)'); xlabel('Return (%)'); ylabel('Counts'); print('hist100_returns.jpg'); printf('making plot 4n'); fflush(stdout); determine(4) hist(returns, 100, 1.0); title('Normalized Returns'); xlabel('Return (%)'); ylabel('Normalized Counts'); print('hist_norm_returns.jpg'); printf('making plot 5n'); fflush(stdout); determine(5) m = imply(returns); sigma = std(returns); x = (-100:100); plot(x, mygauss(x, m, sigma)); title('Gaussian with Identical Imply/Customary Deviation'); xlabel('Return (%)'); ylabel('Likelihood'); print('gauss_model.jpg'); % let consumer know processing is finished % in case determine doesn't pop in entrance k_returns = kurtosis(returns); test = sigma*randn(1, size(returns)) + m; k_check = kurtosis(test); m_check = imply(test); sigma_check = std(test); printf('making plot 6n'); fflush(stdout); determine(6) hist(test, 100, 1.0); title('Histogram of Gaussian Mannequin'); xlabel('% Chnage'); ylabel('Counts'); print('hist_gauss.jpg'); printf('ALL DONE'); fflush(stdout); beep()
and the mygauss perform which implements the Gaussian (Regular/Bell Curve) likelihood density perform:
perform [result] = mygauss(x, imply, sigma) norm = 1.0/(sqrt(2*pi) * sigma); exponent = -1.0*((x - imply) ./ sigma).^2; outcome = norm * exp(exponent); finish
Octave helps commonest particular plots akin to stairs plots, bar charts, pie charts, and so forth.
Stairs Plot
It is a stairs plot of the fuel value time sequence knowledge for the primary few years (discover the steps or stairs within the plot). THis is generated utilizing the Octave stairs perform
Stem Plot
That is the so-called stem plot (Octave stem perform):
Bar Chart
It is a bar chart (Octave bar perform). On Home windows, the bar perform appears to have bother with giant quantities of knowledge in contrast to the opposite plotting features.:
Horizontal Bar Chart
It is a horizontal bar chart (Octave barh perform). On Home windows, the bar perform appears to have bother with giant quantities of knowledge in contrast to the opposite plotting features.
Full Supply Code
The plots above had been generated utilizing the next Octave code:
% common plot determine(1) plot(unleaded_time(1:36), unleaded_price(1:36)); title('plot(time, value) Common Plot'); xlabel('Yr'); ylabel('Worth'); print('regular_plot.jpg'); % determine(2) stairs(unleaded_time(1:36), unleaded_price(1:36)); title('stairs(time, value) Stairs Plot'); xlabel('Yr'); ylabel('Worth'); print('stairs_plot.jpg'); % determine(3) stem(unleaded_time(1:36), unleaded_price(1:36)); title('stem(time, value) Stem Plot'); xlabel('Yr'); ylabel('Worth'); print('stem_plot.jpg'); % determine(4) bar(unleaded_time(1:10), unleaded_price(1:10)); title('bar(time, value) Bar Chart'); xlabel('Yr'); ylabel('Worth'); print('bar_plot.jpg'); determine(5) barh(unleaded_price(1:10)); title('barh(value) Horizontal Bar Chart'); xlabel('Yr'); ylabel('Worth'); print('barh_plot.jpg'); beep();
Octave can generate commonplace pie charts utilizing the pie perform:
That is the Octave code for the pie chart above (NOTE using the cellstr(‘nation identify’) syntax — that is wanted);
% allegedly confirmed oil reserves pie chart %Venezuela 297 %Saudi Arabia 267 %Canada 179 %Iraq 143 %Iran 138 %Kuwait 104 reserves = [ 297, 267, 179, 143, 138, 104 ]; names = [ cellstr('Venezuela (297)'), cellstr('Saudi Arabia (267)'), cellstr('Canada (179)'), cellstr('Iraq (153)'), cellstr('Iran (138)'), cellstr('Kuwait (104)') ]; pie(reserves, names, [1 0 0 0 0 0]); title('Pie Chart of Six Larges Oil Nations'); xlabel('Billions of Barrels of Oil'); print('pie_reserves.jpg');
The third argument to pie (after names ) tells Octave to “explode” the primary wedge (Venezuela).
Octave has features to plot an show three dimensional knowledge and features:
The 2 3D plots above had been generated utilizing the built-in peaksand sombrero check features. It’s doable to compute and show virtually any 3D floor utilizing the meshgrid perform and 3D show features akin to plot3, surf, mesh, contour, and quiver.
Meshgrid
For individuals coming from one other kind of programming such because the C household of langauges, the meshgrid idea and performance is new and should take a bit of getting used to. A meshgrid is principally a quite simple idea which can be very highly effective. Octave represents virtually the whole lot as a “matrix” or multi-dimensional array. That is the supply of a lot of the ability of Octave. One can typically keep away from explicitly coding loops over the weather of the Octave matrix. This speeds growth and reduces errors.
A meshgrid is a two (or larger) dimenaional array during which the weather of the array are the spatial location (x or y coordinate often) of the related factor of a spatial grid (the mesh grid). Right here is a few Octave code which explicitly computes and plots the sombrero perform:
ticks = [-10.0:0.5:10.0]; [x, y] = meshgrid(ticks, ticks); z = sin (sqrt (x.^2 + y.^2)) ./ (sqrt (x.^2 + y.^2)); surf(x,y,z); title('sombrero utilizing meshgrid'); print('sombrero_meshgrid.jpg');
On this instance, the Octave perform meshgrid returns two arrays x and y which contin the x and y corrdinates respectively for the mesh grid parts. On this case, the x and y positions of the grid are specified by the one dimensional ticks array. The ticks run from -10 to 10.0 in steps of 0.5., a complete of 41 ticks. The x array generated by meshgrid is a 41 by 51 array with the x coordinate of every factor. The y array is a 41 by 41 factor array with the y coordinate of every factor.
The meshgrid permits one to precise 3D surfaces or features in Octave in a easy intuitive compact method:
z = sin (sqrt (x.^2 + y.^2)) ./ (sqrt (x.^2 + y.^2));
On this instance, z is a two dimensional array (matrix) with the perform worth on the xand y coordinates specified by every grid level within the arrays xand y. Then, one can show the floor utilizing show features akin to surf, mesh, and so forth. It often takes some observe to get used to utilizing meshgrid if one is just not aware of the idea.
Contour Plot
Octave can create contour plots utilizing the contourfunction.
Vector Subject Plot
Octave can create vector subject plots utilizing the quiver (as in quiver of arrows) perform:
These 3D plots had been generated with the next Octave code:
% 3d graphics % assessments determine(1); sombrero(); print('sombrero.jpg'); pause(1); determine(2); peaks(); print('peaks.jpg'); % meshgrid determine(3); ticks = [-10.0:0.5:10.0]; [x, y] = meshgrid(ticks, ticks); z = sin (sqrt (x.^2 + y.^2)) ./ (sqrt (x.^2 + y.^2)); surf(x,y,z); title('sombrero utilizing meshgrid'); print('sombrero_meshgrid.jpg'); % plot3 determine(4); ticks = [-10.0:0.5:10.0]; [x, y] = meshgrid(ticks, ticks); z = sin (sqrt (x.^2 + y.^2)) ./ (sqrt (x.^2 + y.^2)); plot3(x,y,z); title('sombrero utilizing plot3'); print('sombrero_plot3.jpg'); % mesh determine(5); ticks = [-10.0:0.5:10.0]; [x, y] = meshgrid(ticks, ticks); z = sin (sqrt (x.^2 + y.^2)) ./ (sqrt (x.^2 + y.^2)); mesh(x,y,z); title('sombrero utilizing mesh'); print('sombrero_mesh.jpg'); % contour determine(6); ticks = [-10.0:0.5:10.0]; [x, y] = meshgrid(ticks, ticks); z = sin (sqrt (x.^2 + y.^2)) ./ (sqrt (x.^2 + y.^2)); contour(x,y,z); title('sombrero utilizing contour'); print('sombrero_contour.jpg'); % quiver determine(7); ticks = [-10.0:0.5:10.0]; [x, y] = meshgrid(ticks, ticks); z = sin (sqrt (x.^2 + y.^2)) ./ (sqrt (x.^2 + y.^2)); theta = atan2(y, x); quiver(x,y, z.*cos(theta), z.*sin(theta)); title('sombrero vector subject utilizing quiver'); print('sombrero_quiver.jpg'); % all performed disp('ALL DONE!'); beep();
Debugging Octave
Octave has cryptic error messages. These messages virtually all the time appropriately establish the road of code that’s in error. The verbal descripton of the error is usually incoprehensible and could also be flawed. The column quantity reported for the situation of an error within the line is usually flawed, for instance indicating the beginning of the expression on the fitting hand facet of an task assertion the place the issue is later within the line of code.
If a consumer can not spot the error by studying the road of code, a typical occurence, it’s often greatest to transform the road of code into a number of traces of code with every lnew line of code representing a sub-expression o f the unique line of code. This strategy will often slender the error/bug all the way down to a particular image and establish the particular error.
Octave helps each true-matrix operations and factor by factor (aka element-wise) operations. For instance, A*B is true-matrix multiplication if A and B are matrices. A.*B is factor by factor multiplication during which every factor is multiplied by its corresponding factor within the different matrix. It’s straightforward to mistakenly use * the place one ought to use .* or .* the place one ought to use * in Octave. Pay shut consideration to th edistincition between the true matrix and element-by-element operators.
Octave has intensive in-built plotting and graphics features. There are just a few weaknesses, notably some issues with the bar chart features, not less than within the Home windows model of Octave 3.2.4. Customers coming from a distinct kind of programming background such because the C household of languages might have a bit of time and observe to regulate to the meshgrid idea. The plotting and graphics funsions of Octave are greater than enough for all widespread scientfic, engineeering, and common analytical duties, each two and three dimensional.
© 2011 John F. McGowan
In regards to the Writer
John F. McGowan, Ph.D. is a software program developer, analysis scientist, and advisor. He works primarily within the space of complicated algorithms that embody superior mathematical and logical ideas, together with speech recognition and video compression applied sciences. He has intensive expertise growing software program in C, C++, Visible Primary, Mathematica, MATLAB, and plenty of different programming languages. He’s most likely greatest identified for his AVI Overview, an Web FAQ (Incessantly Requested Questions) on the Microsoft AVI (Audio Video Interleave) file format. He has labored as a contractor at NASA Ames Analysis Middle concerned within the analysis and growth of picture and video processing algorithms and expertise. He has revealed articles on the origin and evolution of life, the exploration of Mars (anticipating the invention of methane on Mars), and low-cost entry to area. He has a Ph.D. in physics from the College of Illinois at Urbana-Champaign and a B.S. in physics from the California Institute of Expertise (Caltech). He could be reached at [email protected].
Sponsor’s message: Take a look at Math Higher Defined, an insightful e book and screencast sequence that can show you how to see math in a brand new gentle and expertise extra of these superior “aha!” moments when concepts all of a sudden click on.