Julia is a programming language for technical computing. It was designed and developed to address the requirements of high-performance numerical and scientific computing, and you can also develop general-purpose programs in Julia.
Julia tries to replace R, MATLAB, Octave and the NumPy module of Python in arithmetic computing by counting on its faster performance. The design and implementation of Julia is based on three principles: it has to be fast, expressive and a dynamic programming language. The core of Julia is written in C, but the rest is written in Julia itself!
On an Ubuntu or Debian system, you can install Julia by executing apt-get install julia as root, then check the installed version of Julia with julia –v. The Julia library provides libraries for linear algebra, random number generation, signal processing and string processing. We will present four Julia packages used for drawing and plotting.
1. The Julia shell
Using Julia, you are mainly going to interact with the Julia shell that you can execute by just typing julia. The Julia shell is the best place to discover the language and try to understand its various features. You can exit the Julia shell by pressing Ctrl+D or by typing quit().
As most of the presented packages need a graphical user interface, you might need to execute the next command as root before continuing, in order to install some of the libraries that are required:
# apt-get install libcairo2-dev libpango1.0-dev
zlib1g-dev tk-dev tcl-dev
2. Install a Julia package
Plotting functionality isn’t included within the core Julia system. To add plotting functionality you will need to install external Julia packages. Therefore, before doing any plotting in Julia, you will need to use its package management commands to install a package. You only need to do this once for a given computer and it will then be installed and available for all future sessions and users.
The Pkg.add() command installs a new package, whereas the Pkg.rm() command deletes an existing package.
3. The TextPlots package
TextPlots is a simple plotting library that generates terminal plots using Braille characters. It enables you to plot any continuous real-valued function or any collection of data points to choose.
As all packages define and use a function that is called plot(), if you try to load another package when the TextPlots package is already loaded, you will get the following warning message shown on-screen:
Warning: using Winston.plot in module Main conflicts with an existing identifier.
4. The Winston package
Winston is a handy and easy-to-use Julia package. Apart from the plot() command that is used for plotting, Winston offers the oplot() command that lets you add objects into existing plots.
If you only want to do basic drawing, then you should start experimenting with Winston. If not, the next two packages are more advanced but have a steeper learning curve.
5. The PyPlot package
This package provides a Julia interface to the Matplotlib plotting library from Python, and specifically to the matplotlib.pyplot module. As a consequence, you will need to have the Python Matplotlib library installed on your machine in order to use PyPlot. If you don’t then you’ll get an error message after executing the using PyPlot command in the Julia shell. The good thing is that PyPlot works with little or no overhead because arrays are passed without making a copy.
6. The Gadfly package
Gadfly is another Julia package that can do drawing. Its interface is similar to the R ggplot2 package. As a result, the Gadfly package is the most powerful of all four packages that we have presented, but it is the most difficult to learn. The output of Gadfly is automatically displayed at a web browser window.
7. Plot a function
You can plot the f(x)=cos(x) function using TextPlots as shown below:
using TextPlots;
plot(cos)
The same plot can be done in Winston as follows:
using Winston;
x = linspace(0, 3pi, 100)
c = cos(x)
p = FramedPlot(title=“Using Winston Package”,
xlabel=“X label”, ylabel=“Y label”)
add(p, Curve(x, c, color=“red”))
Gadfly can also plot the f(x)=cos(x) function:
using Gadfly;
plot([cos], 0, 25)
If you use PyPlot, it is recommended that you execute
the following commands:
using PyPlot;
x = [-2* pi:0.01: 2* pi];
plot(x, cos(x), “.”)
8. Beautify the Gadfly output
The next commands enhance the previously generated Gadfly output by making it more elegant:
plot([cos], 0, 25, Guide.xticks(ticks=[1:1:25],
orientation=:vertical),
Guide.yticks(ticks=[-2:1:2]),
Guide.ylabel(“Drawing the f(x)=cos(x) function”),Guide.
xlabel(“X Value”), Guide.title(“For a LUD article”),
Theme(default_color=color(“#FF0022”), default_point_
size=2pt,
panel_fill=color(“#BBBBBB”), panel_
stroke=color(“Blue”), line_width=2px))
9. Various options of the TextPlots package
The following command plots two functions on
the same output:
plot([x-> cos(x), x-> x/3], -3:3)
The subsequent command removes the border from the output of TextPlots:
plot([x-> cos(x), x-> x/3], -3:3, border=false)
Similarly, the next command removes the border, title and labels from the output:
plot([x-> cos(x), x-> x/3], -3:3, border=false,
title=false, labels=false)
Finally, the following command draws pairs of points on the screen (a scatter plot):
plot([-1, 1, 1, 1], [0, -1, 1, 0])
10. Draw a histogram using Gadfly
Gadfly can easily plot histograms. The following draws a histogram with 1,000 randomly generated values:
julia> plot(x=randn(1000), Geom.
histogram(bincount=100))
The bincount variable defines the number of equal-width bins in the given range.
Changing the bincount value may change the look of the histogram. There is no best or ideal number of bins; different bin sizes can reveal different characteristics of the data.
11. Plot two or more functions with Gadfly
Gadfly can easily let you plot two or more functions on the same output. The following command draws the cos(x), sin(x) and tan(x) functions on the same plot:
julia> plot([cos, sin, tan], -pi, pi)
Gadfly automatically inserts the stylish legend at the right side of the output.
12. Draw box plots using Gadfly
A box plot can give you information regarding the shape, variability and median of a statistical data set and enables you to detect outliers quickly and clearly. Gadfly can easily draw a box plot with random values by using the following command below:
julia> plot(x=randn(20), y=randn(30), Geom.boxplot)
13. Get data from external files
Julia lets you read a text file, import its data and assign it to a new variable to use in your code. The following command reads a file called test.csv and declares that values on the same line are separated using commas:
data = readdlm(“test.csv”,‘,’)
Should you wish to learn more about the readdlm() function, you can type help(readdlm) inside the Julia shell. It’s easy to separate the values from the various columns and assign them to new variables:
C1 = data[:,1];
C2 = data[:,2];
Please note that indices in Julia start at 1 instead of 0.
14. Save the output to an image file
Most of the packages enable you to save the generated output to a file as an image. As you can understand, there is no point of saving the output of TextPlots to a file – you can just copy and paste it. The command for saving the current Winston graph into a file named mySave.png, is the following:
julia> savefig(“mySave.png”)
The command for saving the current Gadfly graph into a file named gadSave.png is shown below:
julia> draw(PNG(“gadSave.png”, 10cm, 5cm),
plot([cos], 0, 25))
Alternatively, you can use the following equivalent technique:
julia> p = plot([cos], 0, 25)
julia> draw(PNG(“gadSave.png”, 10cm, 5cm), p)
The general idea here is that you need to wrap your plot in a function to draw it.
Lastly, saving a graph generated with PyPlot is also easy – once you’re done with drawing, just execute the next command:
julia> savefig(“pyPlotSave.png”, format=“png”)
Please note that the savefig() function does not belong to the Julia programming language. As a result, it is not implemented in Gadfly.
15. Draw a pie chart and histogram using PyPlot
The following code produces a beautiful pie chart using the PyPlot package:
using PyPlot;
sample = [12, 3, 5, 10]
p = pie(sample,shadow=true,startangle=90,autopct=“
%1.1f%%”)
Similarly, you can draw a histogram with 1,000 random numbers as shown:
using PyPlot;
h = PyPlot.plt.hist(randn(1000),15)
grid()
16. Draw in 3D with PyPlot
The following PyPlot code draws a suitable function
in 3D space:
using PyPlot;
ax = gca(projection=“3d”);
X = linspace(-5, 5, 300);
Y = linspace(-5, 5, 300);
R = linspace(-2pi, 2pi, 300);
X, Y = (X,Y);
R = sqrt(X.^2 + Y.^2);
Z = cos(R);
surf = plot_surface(X, Y, Z, rstride=1, cstride=1,
linewidth=1, antialiased=false);
plot3D(X,Y,Z);
plt.show()
17. Create a contour plot using Gadfly
The command below generates an impressive output with the help of Gadfly:
julia> plot((x,y) -> x^3 – y^3, -20, 20, -20, 20,
Stat.contour(samples=50, levels=100))
This type of graph is called a contour plot, which consists of contour lines. A contour line of a function of two variables is a curve along which the function has a constant value.
18. Final thoughts
If you’re going to learn just one package then Gadfly is the way to go. However, if you need to generate naive plots then TextPlots will be handy and easy to learn. If you’re already familiar with Python and matplotlib.pyplot, PyPlot will be the most reasonable choice for you. If it’s an easy-to-learn package with more capabilities than TextPlots that you’re after, you should definitely consider Winston.
There is another Julia package called Gaston that is a wrapper for Gnuplot and can also be used for drawing and plotting. The final choice is yours!
from Linux User & Developer – the Linux and FOSS mag for a GNU generation http://ift.tt/1ociDRS
via IFTTT
No comments:
Post a Comment