Creating Graphics with pygal - jordy33/turbogears_tutorial GitHub Wiki
Open file setup.py and modify install_requires with the following code:
install_requires = [
"TurboGears2 >= 2.3.11",
"Beaker >= 1.8.0",
"Kajiki >= 0.6.3",
"Mako",
"zope.sqlalchemy >= 0.4",
"sqlalchemy",
"alembic",
"repoze.who",
"tw2.forms",
"tgext.admin >= 0.6.1",
"WebHelpers2",
"transaction <= 2.0.2",
"requests",
"pygal"
]
Activate the virtual environment and reinstall imports
cd ~
cd myprojectenv
workon myprojectenv
pip install -e .
In template directory add graph.mak with the following code:
<%inherit file="local:templates.master"/>
<%def name="title()">
Learning TurboGears 2.3: Quick guide to the Quickstart pages.
</%def>
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Graph ${item} Example</h2>
</div>
<div class="container" align="left">
<embed type="image/svg+xml" src=${graph_data} style='max-width:350px'/>
</div>
</div>
</div>
Add the following code to root.py
@expose('myprojectname.templates.graph')
def graph1(self):
graph = pygal.Line()
graph.title = 'Programming languages preference over time.'
graph.x_labels = ['2011', '2012', '2013', '2014', '2015', '2016']
graph.add('Python', [15, 31, 89, 200, 356, 900])
graph.add('Java', [15, 45, 76, 80, 91, 95])
graph.add('C++', [5, 51, 54, 102, 150, 201])
graph.add('All others combined!', [5, 15, 21, 55, 92, 105])
graph_data = graph.render_data_uri()
return dict(item=1,graph_data=graph_data)
@expose('myprojectname.templates.graph')
def graph2(self):
bar_chart = pygal.Bar() # Then create a bar graph object
bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) # Add some values
graph_data = bar_chart.render_data_uri()
return dict(item=2,graph_data=graph_data)
@expose('myprojectname.templates.graph')
def graph3(self):
pie_chart = pygal.Pie()
pie_chart.title = 'Browser usage in February 2012 (in %)'
pie_chart.add('IE', 19.5)
pie_chart.add('Firefox', 36.6)
pie_chart.add('Chrome', 36.3)
pie_chart.add('Safari', 4.5)
pie_chart.add('Opera', 2.3)
graph_data = pie_chart.render_data_uri()
return dict(item=3, graph_data=graph_data)
Test the code:
http://localhost:8080/graph1
http://localhost:8080/graph2
http://localhost:8080/graph3
Click here for pygal manual