Making Graphs using Elixir inside Jupyter Notebook

Jupyter Notebook is known for being an interactive workbench for Python code. However, you can actually use it with the Elixir programming language.

This assumes you already have Python (3.7.3), Jupyter Notebook (5.7.8), and Elixir (1.8.1) installed. Then you just need to install Elixir's Jupyter kernel:

$ git clone https://github.com/pprzetacznik/IElixir.git
$ cd IElixir
$ mix deps.get
$ MIX_ENV=prod mix compile
$ ./install_script.sh

After that you can launch Notebook as usual:

$ jupyter notebook

Now you will have the option of creating a new Elixir notebook.

Installing Hex Packages

Of course what we can accomplish would be pretty restrictive without using any libraries. To use Hex packages inside Notebook, we can use the Boyle library like this:

# make a new environment
Boyle.mk("project1")
Boyle.activate("project1")
# install package to this environment
Boyle.install({:timex, "~> 3.1"})

With the package installed, we can use it as usual:

You can use a previously created environment on another notebook like this:

Boyle.list() # find the environment name
Boyle.activate("project1") # load it

Graphing with Elixir

Now comes the fun part. First install the required libraries. Explot is a wrapper for Matplotlib.

Boyle.mk("graph")
Boyle.activate("graph")
Boyle.install({:explot, "~> 0.1.0"})
Boyle.install({:dataframe, "~> 0.3.1"})

After that you can use plot_command to graph:

plot = Explot.new()
command = "scatter([0, 1, 2, 3], [0, 1, 4, 9])"
Explot.plot_command(plot, command)
Explot.show(plot)

The graph is not displayed inline but on another window which is annoying, but other than that it works great.

To draw a set of points, you can use the unzip method.

{xs, ys} = 0..3
  |> Enum.map(& {&1, &1 * &1})
  |> Enum.unzip()
xs_str = inspect(xs, limit: :infinity)
ys_str = inspect(ys, limit: :infinity)

plot = Explot.new()
command = "scatter(#{xs_str}, #{ys_str})"
Explot.plot_command(plot, command)
Explot.show(plot)

Which will draw the same graph as the first one.

Here's one example of a more interesting graph:

You can change the styling of the plot like this:

# set size (s) and opacity (alpha)
command = "scatter(#{xs_str}, #{ys_str}, s=25.0, alpha=0.3)"
Explot.plot_command(plot, command)
# give title
Explot.title(plot, "y=sin(x)")

Have fun!