Learn about

How to use Chart.JS in Phoenix | Elixir Advanced

Charts are the good-looking way of data

Blackode
Blackode
Oct 3 · 5 min read
Image for post
Image for post
Logos are the properties of respective company

In this article, we are going to use Chart.JS, a Node Library in a Phoenix application. I hope you already know how to work with Phoenix.

Here, we try to replicate a company’s progress yearly. We also provide UI for adding year based progress to our database.

The whole process involves 5 steps.

Let’s dive in.

At the moment of writing this article , I am using the following configuration.

Hex:    0.20.5
Elixir: 1.10.4
OTP: 23.0.3
Built with: Elixir 1.10.0 and OTP 21.3

Step1 — Creating A New Phoenix Project

mix phx.new hello

Create a new Phoenix project using the above command and run the necessary commands to set up the project with a database and node modules. You can name the project as you like.

Here, I am leaving the database with the default configuration. However, you can configure your database in config/dev.exs and run: mix ecto.create .

Step2 — Generating a Migration & Schema using phx.gen

mix phx.gen.html Progress Revenue revenues year:integer amount:float

The first argument Progress is the context module followed by the schema module Revenue and its plural name revenues used as the schema table name. We are not going deeper here as I hope you are familiar with these concepts.

Add the resource to your browser scope in lib/hello_web/router.ex:

resources "/revenues", RevenueController

Remember to update your repository by running migrations:

 mix ecto.migrate

Step3 — Adding Data

If everything went fine, you can visit the http://localhost:4000/revenues there you can see a link to add new revenue.

Image for post
Image for post
/revenues

Use that link to add a revenue value for different years. For good visibility, add at least 5 different years.

After adding data, the ui might be looking like in the following screenshot when you visit the path /revenues.

Image for post
Image for post
/revenues

Step 4 — Chart.Js Setup using NPM

npm install chart.js --prefix assets --save

Go to folder assets/js and create a file with the name linechart.js. You can name the file to your convention. Since we are developing the linechart over the data, I named it as alinechart.js.

This file contains the code to create a chart with the dynamic data.

In this file, we define how our chart should look like. Here, we use two dynamic variables named chart_data and chart_labels. You can name them as you like.

We will make sure of the above mentiond varibles will available in the template we use this linechart.js file.

linechart.js

You have to make a small change here. We need to add a new entry for our linechart.js file.

As we know, in the entire application we use app.js. But, we don’t want this linechart.js to be available on every template. We need this on the specific template we wish to be. For that, we have to make a new entry like in the following way.

Open the file assets/webpack.config.js file and add the following line under entry section.

entry: {
app: glob.sync("./vendor/**/*.js").concat(["./js/app.js"]),
linechart: glob.sync("./vendor/**/*.js").concat(["./js/linechart.js"])
},

The bold and italic line is our new entry for linechart.js file. Don’t forget to add coma , before adding the line.

The Chart.js setup has been completed.

Step 5 — Creating a Chart using linechart.js

This going to be our final major step for creating a chart.

Here, we use the same template that lists the revenues.

Add the following lines in at the end of the template file templates/revenue/index.html.eex.

template for line chart

The noticeable lines of code are

<canvas id="lineChart" width="100%" height="100%"></canvas>

This is the canvas with the id lineChart that we use to render the chart in our linechart.js file.

window.chart_data = <%= raw(Jason.encode!(fetch_chart_data @revenues)) %>window.chart_labels = <%= raw(Jason.encode!(fetch_chart_labels @revenues)) %>

We are making sure of the dynamic variables chart_data and chart_labels are available. The window.variableName means that the variable is being declared at the global scope.

Here, we used the functions fetch_chart_data/1 and fetch_chart_labels/1 which gives the list of amount values and list of years respectively. Soon we are going to develop these functions inside the view file revenue_view.ex associated with this template.

<script src='<%= Routes.static_path(@conn, "/js/linechart.js") %>' type="text/javascript"></script>

Above line simply loads our linechart.js file in this particular template.

Add the following lines of code inside the view file views/revenue_view.ex

def fetch_chart_data(revenues) do
Enum.map(revenues, & &1.amount)
end
def fetch_chart_labels(data_packets) do
Enum.map(revenues, & &1.year)
end

It just prepares the data according to our chart representation. Nothing much to concentrate here.

That’s the end of the Coding part.

Now visit the path /revenues.

This time, you will see the chart under the table section popping up like in the following screenshot.

Image for post
Image for post
Data Table & Chart

The following screeenshot gives the idea of changed files

Image for post
Image for post

Now it’s your time to create beautiful charts.

Happy Coding !!

Join Our Telegram Channe Blackoders

Check out the GitHub repository on Killer Elixir Tips

Image for post
Image for post

Glad if you can contribute with a ★

Coding, thoughts, and ideas.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store