SoFunction
Updated on 2025-04-11

Sample code for creating interactive charts using Pygal

Create interactive charts with Pygal

1. What is Pygal?

Pygal is a Python chart library for generating high-quality, scalable (SVG format), interactive charts. Unlike traditional chart libraries, Pygal's output is based on vector graphics, which means the chart will not be distorted at any resolution, making it ideal for embedding web pages or used as high resolution presentations.

2. Characteristics of Pygal

  • Supports multiple chart types: Including line charts, bar charts, pie charts, funnel charts, etc.
  • SVG format output: The chart is clear and scalable.
  • Lightweight: Suitable for generating simple static charts.
  • Interactive: Supports mouse over to display data prompts (need to be viewed in the web environment).
  • Simple and easy to use: Use Python to quickly generate professional charts.

3. Install Pygal

Install using pip:

pip install pygal

4. Quick Start Example

Here is an example of creating a simple line chart:

import pygal

# Create a line chartline_chart = ()
line_chart.title = 'Annual Sales Data'
line_chart.x_labels = ['2019', '2020', '2021', '2022', '2023']
line_chart.add('Product A', [150, 200, 180, 220, 260])
line_chart.add('Product B', [120, 180, 150, 190, 230])

# Save the chart as an SVG fileline_chart.render_to_file('sales_chart.svg')
print("The chart has been saved as sales_chart.svg")

After running, generatedsales_chart.svgFiles can be viewed in the browser and support interactive hover function.

5. Commonly used chart types

Pygal supports multiple chart types, and the following are some examples of common types:

(1) Bar chart

import pygal

bar_chart = ()
bar_chart.title = 'Quarterly Revenue Comparison'
bar_chart.x_labels = ['Q1', 'Q2', 'Q3', 'Q4']
bar_chart.add('2022', [500, 600, 700, 800])
bar_chart.add('2023', [550, 650, 750, 850])

bar_chart.render_to_file('bar_chart.svg')

(2) Pie chart

import pygal

pie_chart = ()
pie_chart.title = 'market share'
pie_chart.add('Brand A', 40)
pie_chart.add('Brand B', 30)
pie_chart.add('Brand C', 20)
pie_chart.add('other', 10)

pie_chart.render_to_file('market_share.svg')

(3) Funnel diagram

import pygal

funnel_chart = ()
funnel_chart.title = 'Sales funnel'
funnel_chart.add('Potential Customers', 1000)
funnel_chart.add('Intentional Customer', 600)
funnel_chart.add('Buy Customer', 300)

funnel_chart.render_to_file('funnel_chart.svg')

(4) Radar diagram

import pygal

radar_chart = ()
radar_chart.title = 'Skills Assessment'
radar_chart.x_labels = ['Python', 'SQL', 'Data Analysis', 'Machine Learning', 'Web Development']
radar_chart.add('Alice', [90, 85, 80, 70, 75])
radar_chart.add('Bob', [80, 70, 90, 85, 80])

radar_chart.render_to_file('radar_chart.svg')

6. Advanced features

(1) Custom styles

Pygal provides built-in styles and supports custom styles.

from  import DarkStyle

line_chart = (style=DarkStyle)
line_chart.title = 'Custom Style Example'
line_chart.add('Data 1', [1, 3, 5, 7, 9])
line_chart.render_to_file('custom_style.svg')

(2) Dynamically load data

import pygal
import random

dynamic_chart = ()
dynamic_chart.title = 'Dynamic data loading'

# Dynamically generate datafor i in range(5):
    data = [(0, 100) for _ in range(10)]
    dynamic_chart.add(f'series {i + 1}', data)

dynamic_chart.render_to_file('dynamic_chart.svg')

(3) Data log scaling

Logarithmic coordinates can be used when the data range span is large:

from pygal import LogarithmicChart

log_chart = LogarithmicChart()
log_chart.title = 'Logular Scale Example'
log_chart.add('Data 1', [1, 10, 100, 1000, 10000])
log_chart.add('Data 2', [5, 50, 500, 5000, 50000])

log_chart.render_to_file('log_chart.svg')

7. Deployment and Integration

The SVG files generated by Pygal charts can be directly embedded in HTML pages, or can be dynamically generated and displayed through web frameworks such as Flask or Django.

Example: Using Pygal in Flask

from flask import Flask, render_template_string
import pygal

app = Flask(__name__)

@('/')
def index():
    # Create a chart    bar_chart = ()
    bar_chart.title = 'Sample Chart'
    bar_chart.add('Data A', [10, 20, 30, 40])
    bar_chart.add('Data B', [15, 25, 35, 45])

    # Render as HTML embedded code    chart = bar_chart.render(is_unicode=True)
    html_template = """
    <!DOCTYPE html>
    <html>
    <head><title>Pygal Example</title></head>
    <body>
        <h1>Pygal chart</h1>
        {{ chart | safe }}
    </body>
    </html>
    """
    return render_template_string(html_template, chart=chart)

if __name__ == '__main__':
    (debug=True)

8. Summary

Pygal is a powerful, simple and easy-to-use Python chart library suitable for generating high-quality interactive charts in SVG format. Its rich chart types and simple API make it a powerful tool for data visualization and presentation. If your project needs to generate lightweight, interactive charts, Pygal is a worthwhile choice!

9. Pros and cons of Pygal

advantage

  1. High-quality output:SVG format ensures that the charts are not distorted at any resolution, making them ideal for embedding web pages or for publishing.
  2. Interactive: Mouse hover can display data details and improve user experience.
  3. Simple and easy to use: Only a few lines of code can generate professional charts.
  4. Various chart types: Supports various types such as bar charts, line charts, radar charts, funnel charts, etc.
  5. Lightweight: Low system resources requirements, which are very suitable for quickly generating charts.
  6. Highly customizable: Supports customization of themes, styles, colors, fonts, etc.

shortcoming

  1. Limited functions: No complex dynamic charts (such as dynamic updates, animation effects, etc.) are supported.
  2. Weak processing of big data: When rendering a large number of data points, the SVG size will increase significantly, which will affect performance.
  3. Browser compatibility: Some old browsers may have poor support for SVG, and users need a modern browser to get the best experience.

10. Application scenarios

(1) Data display

Pygal is ideal for web data presentation, especially when it is necessary to generate clear, high-resolution graphs.

(2) Data Report

Because Pygal generates SVG files that can be embedded directly into documents in PDF, HTML, or other formats, they are particularly suitable as a charting tool in business or academic reports.

(3) Teaching and training

In teaching, Pygal's simple grammar and intuitive output are ideal as a beginner for students to learn data visualization.

(4) Embedded systems or lightweight web applications

Because Pygal is lightweight, it is ideal for use in resource-limited embedded systems or lightweight web applications.

11. Practical advice

(1) Data point optimization

For charts containing large amounts of data, such as time series, the data can be sampled or aggregated to reduce the size of the generated SVG file. For example:

import pygal
import random

# Simulate large amounts of datadata = [(0, 100) for _ in range(10000)]

# Data sampling: Take one every 10 pointssampled_data = data[::10]

chart = ()
 = 'Line Chart of Sampled Data'
('data', sampled_data)
chart.render_to_file('sampled_chart.svg')

(2) Chart output optimization

To improve loading performance, the SVG chart generated by Pygal can be converted into PNG format for use in non-interactive scenarios:

# Convert SVG to PNG using cairosvgpip install cairosvg
cairosvg  -o 

(3) Integrated front-end framework

By integrating backend frameworks such as Flask, Django, or FastAPI, charts can be generated dynamically and displayed in front-ends such as React or Vue.

12. Comparison of Pygal with other visualization tools

characteristic Pygal Matplotlib Plotly Seaborn
Output format SVG PNG、PDF、SVG HTML、PNG PNG、PDF
Interactive Basic interaction none Highly interactive none
Learning curve Simple medium A little steep Simple
Chart type richness Rich Very rich Very rich Focus on statistics charts
Dynamic update support no no yes no

13. Summary

Pygal is a simple and efficient chart generation tool, especially suitable for scenarios where scalable high-quality charts are needed. Whether it’s fast visualization of data, generating reports, or embedding into web pages, Pygal does a great job. Despite its limitations in dynamics and big data processing, Pygal is still a recommended option for small and medium-sized projects and static data presentation.

If you are looking for a lightweight, easy to use visualization tool, try Pygal. Use it to add a simple and elegant chart to your project!

The above is the detailed content of the sample code for creating interactive charts using Pygal. For more information about creating interactive charts by Pygal, please follow my other related articles!