Using Clojurescript to Make Charts with Raphael.js
October 12, 2014
Setup with Leiningen
First, start a Clojure project using Leiningen with the line
lein new cljs-raphael. It's possible to use the Clojurescript compiler directly, but lein is the way to go if you want to develop other parts your project in Clojure.
Go into the cljs-raphael directory and open up project.clj. Add a Clojurescript dependency:
[org.clojure/clojurescript "0.0-2173"], and add the Clojurescript plugin:
:plugins [[lein-cljsbuild "1.0.2"]]. Your project.clj should look like this:
Next, add your Clojurescript compiler options after the line
:plugins [[lein-cljsbuild "1.0.2"]].
With this configuration, the compiler will look in the
src/cljs_raphael directory for Clojurescript files and compile them to
At this point, run
lein deps to get our Clojurescript dependency installed.
External JS files and index.html
In order for us to write Clojurescript that uses Raphael, we need to include the Raphael SVG library and its corresponding graph library. Download raphael-min.js, g.raphael-min.js, and g.pie-min.js, and place them inside of your
We also need an
index.html page onto which our Clojurescript can render graphs! Add the following into a new file,
Let's put something on the page using Clojurescript. Make a new file,
src/cljs_raphael/pie.cljs, and put this in it:
src/cljs_raphael directory and recompile anytime a .cljs file is saved.
resources/index.html in a browser. You should see "Yeehaw!" on the page.
Making an Animated Pie Chart
Chart-making time! I will create a pie chart based on this demo chart.
First, go to your
pie.cljs file and update the
init function to look like this:
Note that in Clojurescript, we use
(js-obj) functions to create those particular JS data structures in Clojurescript.
Take another look at the dot and dot-dash characters in the Clojurescript above. Something like
(.log js/console "Yeehaw"), with just a dot, correponds to calling an object's function. Meanwhile, something like
(.-onload js/window) corresponds to getting or setting an object's property (here, the window object's onload property).
Now let's add a title. Replace
(other-functions-in-scope) with this:
This corresponds to:
And refresh your page. You should see your pie chart, a legend, and the title!
Next, let's add the fun hover effect. Start by adding this function above
This animates the wedges and corresponding labels when we hover over a pie chart wedge. In order to make this work, I used the
this-as macro to open up access to
Next, add this function also above init. This is the function that will be called when the mouse leaves a wedge.
Lastly, add the following line inside
init to bind those event handler functions to the pie chart wedges.
Refresh your page in the browser. At this point, you should have a sweet animated pie chart - powered by the magical intersection of Clojurescript, the JVM, and interop with RaphaelJS. Get up and start dancing!