Wednesday, June 10, 2015

pygal, a Python SVG charting library

By Vasudev Ram




I came across pygal recently. It is a Kozea project. They also have some other interesting projects, some of which are in Python. lxml is the only needed dependency for pygal.

I tried out a simple example from the pygal site, which generates a graph of Fibonacci numbers, and then enhanced it a bit to add a graph of a univariate quadratic function, which represents a parabola, in the same plot. The quadratic function I used was:

3x^2 + 2x + 4 (three x squared plus two x plus four)

[ Also check out:

Quadratic equations

and

the quadratic formula

if not known (or not remembered from high school mathematics :)

And speaking of quadratics (functions, formulae, equations and so on), also check out my earlier post:

Bhaskaracharya and the man who found zero, which briefly mentioned Brahmagupta, an ancient Indian mathematician, who is supposed to be the discoverer of the number zero, without which practically no modern science or technology (including computers and software :) would be possible. He also gave "the first explicit (although still not completely general) solution of the quadratic equation ax^2 + bx = c", according to the Wikipedia article about him, linked to in the previous sentence.

]

Here is the modified pygal example program, in test_pygal.py:
import pygal

bar_chart = pygal.Bar()
bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
bar_chart.render_to_file('bar_chart.svg')

def quadratic(a, b, c, x):
    return a * x * x + b * x + c

bar_chart.add('Quadratic', [quadratic(3, 2, 4, x) for x in range(1, 10)])
bar_chart.render_to_file('bar_chart.svg')
I ran it with:
py test_pygal.py
[ Learn more about py here: py, the Python Launcher for Windows ]

And here is a screenshot of the output of running the test pygal program:


You can intuitively see that if you drew a curve joining the tops of the green bars in the screenshot, it would approximate a parabola. Parabolas occur a lot in nature too, as do many other mathematical concepts or principles.

- Enjoy.

- Vasudev Ram - Online Python training and programming

Dancing Bison Enterprises

Signup to hear about new products or services that I create.

Posts about Python  Posts about xtopdf

Contact Page

1 comment:

Vasudev Ram said...


Also see this related post I just saw:

Mark Hammond Receives Distinguished Service Award - for many things related to Python on Windows, including the PEP 397 -- Python launcher for Windows.