ajay0221
ajay0221

Reputation: 359

How to generate graphs and charts on the fly using web2py

I am getting data after firing from Databases. I want to generate some basic graphs using this data to interpret the results. I read some posts that Protovis is helpful in achieving this but i can't find much content about it. In ideal scenario I would like to use d3js generated data driven documents.

Upvotes: 0

Views: 2786

Answers (2)

ChrisGuest
ChrisGuest

Reputation: 3608

Here is an example of how to use d3.js in web2py. This works for me using this this d3.js sample from the book, Interactive Data Visualizations for the Web.

Add a controller, controllers/d3js.py

import random 
def histogram():
    dataset = [(random.randint(1,6) + random.randint(1,6)) for i in range(100)]
    return dict(dataset=dataset, title='D3.js Histogram')

Add a view view/d3js/histogram.html that contains your d3.js code utilising the dynamic features that are passed from the controller.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>{{=title}}</title>
        <script type="text/javascript" src="https://d3js.org/d3.v3.min.js" ></script>
    </head>
    <body>
        <script type="text/javascript">

            {{from gluon.serializers import json}}
            var dataset = {{=XML(json(dataset))}};

            //Width and height
            var w = 600;
            var h = 600;
            ...

            //Create SVG element
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);

            ...

        </script>
    </body>
</html>

Upvotes: 1

Boa
Boa

Reputation: 2677

What sort of graphs/charts are you trying to generate? If you're doing basic bar charts, you can generate them server-side using web2py's HTML helpers. Here's an example of a page that does that.

Another option, if I recall correctly, is Massimo's (web2py project leader) Canvas library, which offers a matplotlib interface.

Aside from that, as you've noted, there are plenty of javascript libraries. There's a web2py plugin for Google charts

Upvotes: 0

Related Questions