Skip to content

Instantly share code, notes, and snippets.

@ejucovy
Created June 24, 2010 16:15
Show Gist options
  • Save ejucovy/451637 to your computer and use it in GitHub Desktop.
Save ejucovy/451637 to your computer and use it in GitHub Desktop.
manually building a legend for a g.raphael linechart
raph = Raphael([..]);
chart = raph.g.linechart([..]);
var labels = ["first variable", "second variable", "third variable"];
chart.labels = raph.set();
var x = 15; var h = 5;
for( var i = 0; i < labels.length; ++i ) {
var clr = chart.lines[i].attr("stroke");
chart.labels.push(raph.set());
chart.labels[i].push(raph.g["disc"](x + 5, h, 5)
.attr({fill: clr, stroke: "none"}));
chart.labels[i].push(txt = raph.text(x + 20, h, labels[i])
.attr(raph.g.txtattr)
.attr({fill: "#000", "text-anchor": "start"}));
x += chart.labels[i].getBBox().width * 1.2;
};
@ejucovy
Copy link
Author

ejucovy commented Jun 24, 2010

Hmm, a few notes:

  • chart.lines[i].attr("stroke") fails if you've set "nostroke" to true - chart.lines doesn't exist then. Instead you can use chart.symbols[i][0].attr("fill")
  • When removing the chart, you need to manually remove the labels first - they aren't cleared out automatically: chart.labels.remove(); chart.remove()

@dashko
Copy link

dashko commented Feb 5, 2013

var labels = ["first variable", "cond", "third"];
chart.labels = r.set();
var x = 15; var h = 5;
for( var i = 0; i < labels.length; ++i ) {
var clr = chart.lines[i].attr("stroke");
chart.labels.push(r.set());
chart.labels[i].push(r["circle"](x, h, 5)
.attr({fill: clr, stroke: "none"}));
var a = r["text"](x, h-1000, labels[i]);
a.hide();
chart.labels[i].push(r["text"](x+a.getBBox%28%29.width/2+13, h, labels[i]).attr(txtattr).attr("fill", "#999999"));
console.log(chart.labels[i].getBBox().width);
x += chart.labels[i].getBBox().width+10;
};

@dev-bre
Copy link

dev-bre commented Mar 6, 2013

I got an exception telling: g is undefined at line 10 ... any idea?

@Louhike
Copy link

Louhike commented Mar 20, 2013

In the last version of gRaphaël, "disc" doesn't exist anymore and the functions like "circle" must be called through the Paper object (raph) directly. To make this work, you need to replace raph.g["disc"] by something like raph["circle"].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment