How to make little sparklines


I was asked off list how I created the little sparklines using Matplotlib.

There are two ways I create these:

The live graphs on the demo page (
are created by a great little jquery app (so yeah, not matplotlib):

To get the data to the browser in order to render the sparkline, you
will need some sort of mechanism similar to Ajax (or at least a form of
it) called Comet. There is a great tutorial on using orbited for this here

If any of you need more help doing that, I am happy to provide some
source code examples.

If instead, you want to create static line graphs using matplotlib such
as those on this page: (an

To render static sparklines I use the following matplot lib code:

def render_simple_line(sensors, resolution = 'hour', span = 1,
                           start=None, end=None, fig=None, column=0):
    """Builds a figure that shows the given sensors at the given
resolution and span in the given time period.

    if fig is None:
    axes = fig.add_axes([0.00,0.00,1.0,1.0], axisbg='w', frame_on=False)

    if start is None:
        start =
    if end is None:
        end = start + datetime.timedelta(days=1)
    first_date = start.strftime('%Y-%m-%d')
    last_date = end.strftime('%Y-%m-%d')

    desc = [("mean", pk) for pk in sensors]
    np_table = data_table_matrix(desc, resolution, first_date,
last_date, span )
    #note that np_table[0] is datetime objects and [1] is data
    if np_table.size == 0:
        return None

    #replace nulls with 0
    np_table[1:][np_table[1:] == np.array([None])] = 0
    #replace -ve values
    np_table[1:][np_table[1:] < np.array([0])] = 0


    base = np.zeros(np_table.shape[1])

    color = color_list[column % len(color_list)][1]
    axes.fill_between(np_table[0], base, np_table[column + 1], facecolor
= color)

    return fig

I pass fig in so it is easy to pass a figure from the ipython console,
since ipython makes special figures that are interactive.


PS: Dan - I replied to your email directly but it bounced.