Graphing API

xymostech edited this page Jul 6, 2012 · 6 revisions

Some Usage Examples

All of this is within a div.graphie that takes no attributes, unless you want to update another graph with data-update="previousid".

init({
    range: [[-24, 24], [-18, 18]],
    scale: [20, 30] // a unit square is now 20px wide by 30px high; omit for 40 x 40
});

style({
    stroke: "black",
    strokeWidth: 2 // px; "2px" works too
});

// Two sides of a triangle
path([[0, 0], [1, 0], [0, 1]]);

// A (closed) equilateral triangle
// These are polar coordinates; maybe this is superfluous feature-adding
path([polar(0, 0), polar(1, 0), polar(1, 60), true]);

// Labels for that triangle!
// These are TeXed and pretty
label(polar(0, 0), "A", "below left");
label(polar(1, 0), "B", "below right");
label(polar(1, 60), "C", "above");
label(polar(1, 60), "C", 90); // same as "above"

label([ -3, 4 ], "marcia", "left", {
    labelDistance: 4,

    // this is CSS style, not SVG
    // label styles don't work yet :(
    color: "#fff",
    background: "cornflowerblue"
});

// A big semitransparent purple circle at the origin (radius 17) with a thick
// red stroke
circle([0, 0], 17, {
    fill: "purple",
    stroke: "red",
    strokeWidth: 5,
    opacity: 0.6
});

style({
    stroke: false,
    fill: "yellow",

    //        [  point ,  size  ]
    clipRect: [[-7, -4], [14, 8]]

    // scale, range are probably illegal right here
}, function() {
    // Both of these will be filled with yellow and have no stroke
    // Two tall (8:1 semiaxis ratio) ellipses clipped at the top and bottom
    ellipse([-6, 0], [1, 8]);
    ellipse([6, 0], [1, 8]);
});

// The following arc is *not* yellow or clipped but it probably looks much
// prettier than this nice diagram does
//
//        *
//       /
//      |  (5,0)  *
//       \       /
//        *-___-*
//
arc([5, 0], 4, 120, 360);

// line(a, b) is the same as path([a, b])
line([0, 1], [1, 3], {
    arrows: "->" // or "<->"
});

// Grids always go through the origin
grid([-17, 17], [-13, 13], {
    stroke: "gray",
    step: [4, 3]
});

// Some plots
plot(function(x) {
    // javascript Math is already imported
    return x * sqrt(x);
}, [-6, 6], {
    stroke: "red"
});

plotPolar(function(th) {
    return 2 * sin(4 * th);
}, [0, 2 * PI], {
    stroke: "blue"
});

plotParametric(function(t) {
    //     [  x,        y     ]
    return [sin(t), sin(2 * t)];
}, [0, 2 * PI], {
    stroke: "green"
});

// Event handlers are basically the same as in Raphaël but use our nice coordinates for animations
// This doesn't work yet, sorry.
circle([0, 0], 1).click(function(e) {
    // Grow over one second
    this.animate({
        r: 2
    }, 1000);
});

We also have some additional info on adding interactive elements to your graphs.

Thoughts

  • Degrees are used everywhere an angle is used except as the argument of a polar plot function.