Pygal Tutorial

Pygal Tutorial

Pygal is a dynamic SVG charting library written in Python. It is particularly useful because it can generate charts that are easily embedded in a web page and are interactive.

Below is a basic tutorial on how to use Pygal:

1. Installation

You can install pygal using pip:

pip install pygal 

2. Simple Bar Chart

import pygal # Create a new bar chart bar_chart = pygal.Bar() # Title of the chart bar_chart.title = "Fruits Count" # Add data bar_chart.add('Apples', 10) bar_chart.add('Bananas', 7) bar_chart.add('Oranges', 5) # Save the chart into an SVG file bar_chart.render_to_file('bar_chart.svg') 

This will create a bar chart with counts of three types of fruits and save it to a file named bar_chart.svg.

3. Line Chart

line_chart = pygal.Line() line_chart.title = 'Website Visits Over Time' line_chart.x_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May'] line_chart.add('Visits', [100, 120, 130, 90, 150]) line_chart.render_to_file('line_chart.svg') 

4. Pie Chart

pie_chart = pygal.Pie() pie_chart.title = 'Browser Usage (in %)' pie_chart.add('Chrome', 45.5) pie_chart.add('Firefox', 36.6) pie_chart.add('Safari', 9.9) pie_chart.add('Edge', 4.2) pie_chart.add('Others', 3.8) pie_chart.render_to_file('pie_chart.svg') 

5. Styling

Pygal provides various styles to customize the look and feel of the charts.

from pygal.style import DarkStyle bar_chart = pygal.Bar(style=DarkStyle) bar_chart.title = "Fruits Count in Dark Style" bar_chart.add('Apples', 10) bar_chart.add('Bananas', 7) bar_chart.add('Oranges', 5) bar_chart.render_to_file('styled_bar_chart.svg') 

6. Integration with Flask

You can use Pygal with Flask to render charts directly in your web app.

Here's a simple example:

from flask import Flask, render_template_string import pygal app = Flask(__name__) @app.route("/chart/") def chart(): bar = pygal.Bar() bar.add('Fruits', [10, 7, 5]) chart_data = bar.render_data_uri() return render_template_string(""" <html> <body> <figure> <embed type="image/svg+xml" src="{{ chart_data }}" /> </figure> </body> </html> """, chart_data=chart_data) if __name__ == "__main__": app.run(debug=True) 

In this example, the Flask app dynamically generates a chart using Pygal and renders it directly in the browser.

This is just a basic introduction to Pygal. The library offers many other features and chart types. You can explore the official documentation for more advanced use-cases and customization options.


More Tags

android-broadcast google-kubernetes-engine android-gridview android-activity jersey-2.0 manifest amazon-dynamodb-streams lowercase pyscripter logcat

More Programming Guides

Other Guides

More Programming Examples