Raphael Charting Library

June 29, 2010

I've been looking into the Raphael charting library to replace the Flash Charts on one of my sites with javascript ones, so they're supported on the iphone/ipad. There's very little documentation out there, so here's what I've worked out.

Setup

Here's details of the imports needed.

<script src="/raphael/raphael-min.js" type="text/javascript" charset="utf-8"></script>
<script src="/raphael/g.raphael-min.js" type="text/javascript" charset="utf-8"></script>
<script src="/raphael/g.pie-min.js" type="text/javascript" charset="utf-8"></script>

Pie Chart

The first thing to do is create a Raphael instance. Pass this three things - the value of the id attribute of the div you want to put the content in, the width, and then the height.

var r = Raphael("chart", 500, 240);

Next, create the pie chart. The parameters for this are: Indent from left hand side, indent from top, size of pie chart circle, data (just numbers - doesn't need to be percentages), legend, options.

var pie = r.g.piechart(150, 100, 80, [4,6,2,30], {legend: ["Wins", "Second", "Third", "Unplaced"], legendpos: "east"});

Add a hover effect to make the wedges larger when hovered over, and make the legend bold.

pie.hover(function () {
    this.sector.stop();
    this.sector.scale(1.1, 1.1, this.cx, this.cy);
    if (this.label) {
        this.label[0].stop();
        this.label[0].scale(1.5);
        this.label[1].attr({"font-weight": 800});
    }
}, function () {
    this.sector.animate({scale: [1, 1, this.cx, this.cy]}, 500, "bounce");
    if (this.label) {
        this.label[0].animate({scale: 1}, 500, "bounce");
        this.label[1].attr({"font-weight": 400});
    }
});

Controlling Colours

You can fix the colours for the pie segments with an optional extra parameter:

var pie = r.g.piechart(150, 85, 70, [{{Wins}}, {{TopSixNotWin}}, {{Unplaced}}], {
    legend: ["Wins ({{Wins}})", "Top Six ({{TopSixNotWin}})", "Unplaced ({{Unplaced}})"], 
    legendpos: "east", 
    colors: ["#A01E1E", "#EC6A01", "#1C7B1C"]});

The above example is taken from a django template, hence the values in {{ Brackets }}

References

  • http://raphaeljs.com/
  • http://g.raphaeljs.com/