Search code examples
graphraphaelgraphael

How to add X axis and Y axis labels on Raphael js charts


I'm trying to use Raphael.js to do some nice graphing for data after which I realize there are several limitations to the js which I'm trying to solve.

Does anyone knows how to scale the y axis value dynamically as I've realized that once the values cross >500 , the graphing does not appear at all , only the axes appears with plots at the extreme edges in one line (i.e. over the limit).

Secondly is there a way to add legends or axis labels to the graphs ? Or must graph labels be coded separately as html ?

Thanks Lots !!! Its a great looking tool but it seems quite useless ...


Solution

  • The chart g.bar.js does not have an option to draw axes. If you look inside g.line.js, however, there is a block of code around lines 98-117 (currently) that draws axes:

        var allx = Array.prototype.concat.apply([], valuesx),
            ally = Array.prototype.concat.apply([], valuesy),
            xdim = chartinst.snapEnds(Math.min.apply(Math, allx), Math.max.apply(Math, allx), valuesx[0].length - 1),
            minx = xdim.from,
            maxx = xdim.to,
            ydim = chartinst.snapEnds(Math.min.apply(Math, ally), Math.max.apply(Math, ally), valuesy[0].length - 1),
            miny = ydim.from,
            maxy = ydim.to,
            kx = (width - gutter * 2) / ((maxx - minx) || 1),
            ky = (height - gutter * 2) / ((maxy - miny) || 1);
    
        var axis = paper.set();
    
        if (opts.axis) {
            var ax = (opts.axis + "").split(/[,\s]+/);
            +ax[0] && axis.push(chartinst.axis(x + gutter, y + gutter, width - 2 * gutter, minx, maxx, opts.axisxstep || Math.floor((width - 2 * gutter) / 20), 2, paper));
            +ax[1] && axis.push(chartinst.axis(x + width - gutter, y + height - gutter, height - 2 * gutter, miny, maxy, opts.axisystep || Math.floor((height - 2 * gutter) / 20), 3, paper));
            +ax[2] && axis.push(chartinst.axis(x + gutter, y + height - gutter, width - 2 * gutter, minx, maxx, opts.axisxstep || Math.floor((width - 2 * gutter) / 20), 0, paper));
            +ax[3] && axis.push(chartinst.axis(x + gutter, y + height - gutter, height - 2 * gutter, miny, maxy, opts.axisystep || Math.floor((height - 2 * gutter) / 20), 1, paper));
        }
    

    This can effectively be copy and pasted into the function VBarchart in g.bar.js to give you axes options. A little adjustment to x and y positions will be required, and maxy should probably be set to opts.total to get the scaling right - yes, you will need to fart around with it a bit, but it does work.