RaphaelJS with rotated labels in a bar chart

While doing some simple bar charts using raphaelJS, I ended up having trouble because my labels, which I was placing at the bottom of the chart, were trying to go horizontally, and they were too long to fit. The sensible thing seemed to be to make the labels orient vertically under the bars, like so:

The labels shown above are fairly short, of course, but I have other bar charts with longer labels. As it turned out, trying to get them oriented vertically like this wasn’t straightforward. After making the call to create the bar chart I tried to modify the labels, but it involved making some assumptions about the chart’s data structure, which seemed unwise; and in any case it wasn’t quite working properly.

So, I ended up modifying the raphaelJS code, in the g.bar.js file. I added a new rotate parameter to the label() function which for now just rotates the labels 90 degrees if the parm is true. After more testing I’ll see if it’s useful enough to fix up nicely, in which case I’ll make it take the degrees as the parameter. The tricky part actually ended up being the positioning — if the label gets rotated, it needs to be moved, so the code calculates the length of the text and figures out how much to move it down in order to position it under the bar properly.

So now I just call the bar chart function like so:

bc = r.g.barchart(30, 30, 500, 400, [<%= @values.to_json -%>]).hover(fin, fout).label([<%= @labels.to_json -%>], true, true);

The last parameter sets rotate=true and the other boolean is for isBottom=true, which is the default value.

I forked the raphaelJS code on github, and pushed my changes to my repository, so if you find this useful, go for it: Github. Enjoy.

1 comment
  1. Pranav said:

    I tried this piece of code but its not working. Here is what i did:

    var r4 = Raphael(document.getElementById(‘otpBarChart’),200,200),
    fin2 = function () {
    this.flag = r4.g.popup(this.bar.x, this.bar.y, this.bar.value || “0”).insertBefore(this);
    fout2 = function () {
    this.flag.animate({opacity: 0}, 300, function () {this.remove();});
    r4.g.txtattr.font = “12px ‘Fontin Sans’, Fontin-Sans, sans-serif”;
    r4.g.text(85, 170, “OTP “).attr({“font-size”: 14});
    r4.g.barchart(10,10,150,150,[[0, 85,86],[90,0,0]],{stacked: true, type: “soft”}).hover(fin2, fout2).label([“Required”,”Primary”,”2ndary”],true,true);

    Any suggestion please.

    Also is there any way to control the color of bars??

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: