ToscaWidgets JQuery and Flot Plotting (Tutorialish-ly)

Continuing on from our previous tutorial, here's a quick example showing how to create a Flot plotting library plot using tw.jquery's FlotWidget class.  In our controller module, we'll import the widget and some support functions:

from tw.jquery import FlotWidget
from math import sin,cos
import simplejson

The FlotWidget is part of the core tw.jquery support, but it triggers an error in tw.core < 0.9.8 (0.9.8 should be out in about a week, I'm told), so we have to "patch" the core with this class:

base_FlotWidget = FlotWidget
class FlotWidget( base_FlotWidget ):
"""Hack to work-around bug in ToscaWidgets < 0.9.8"""
def update_params(self, d):
super(base_FlotWidget, self).update_params(d)
if not d.get('data'):
raise ValueError, "FlotWidget must have data to graph"
if not d.get('id'):
d['id'] = 'flot_%s' % str(int(random() * 999))
data = d.get('data', [])
options = d.get('options', {})
"""$.plot( $('#%s'), %s, %s )"""%(, simplejson.dumps( data ), simplejson.dumps( options )
return d

Okay, now that the preliminaries are out of the way, we can create our actual controller method:

def flottest( self, **named ):
"""Test/demo for the Flot plotting widget"""
plot_data = [
for x in range( 0, 200 )
return dict(
plot_data = [
'data':[(x[0],x[1]) for x in plot_data]
'data':[(x[0],x[2]) for x in plot_data]
flot = FlotWidget(
id = 'plotter',
height = "10em",
width = "20em",
label = "Javascript Plotting for TurboGears",
options = dict(
lines = { 'show': True },
points = {'show': True },
page = 'flottest',

The bulk of the code there is just creating a data-set to be displayed.  Here we create a sin/cos plot from 0.0-10.0 .  You will note that we are not using the JQueryCompressed() object we used in our last tutorial.  The FlotWidget automatically includes the JQuery source when invoked.  Our template, as a result, doesn't call jquery(), but otherwise looks very much like the TinyMCE template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns=""

<xi:include href="master.html" />
<meta content="text/html; charset=UTF-8" http-equiv="content-type" py:replace="''"/>
<title>Example Flot Viewer</title>

<div id="flot-test">
<h2>Example Flot Viewer</h2>
${ flot( data = plot_data ) }
<div class="clearingdiv" />

Screenshot The Flot project homepage has lots of samples of how to customize your plots.  Note that if you are plotting time-series data you will need to use time.time() style seconds-since-the-epoch form, rather than datetime.datetime() objects.


  1. Omri

    Omri on 05/19/2010 9:27 a.m. #

    maybe it's a stupid newbie question, but where and how exactly should the patching of the core take place?


Comments are closed.


Pingbacks are closed.