Data visualization With Pygal
Last Updated :
15 Jan, 2025
Pygal is an open-source Python library designed for creating interactive SVG (Scalar Vector Graphics) charts. It is known for its simplicity and ability to produce high-quality visualizations with minimal code. Pygal is particularly useful for web applications, as it integrates well with frameworks like Flask and Django, and its SVG output ensures scalability without loss of quality.
Data visualization With PygalInstalling Pygal for Data Visualization
To get started, you need to install Pygal. You can do this using pip:
pip install pygal
Creating Basic Charts with Pygal
Pygal supports a variety of chart types. Here’s an overview of some popular ones: Let's explore how to create some basic charts using Pygal. Pygal primarily generates charts in SVG (Scalable Vector Graphics) format, which is a vector image format.
1. Bar Charts
Bar charts are used to compare quantities across different categories. It is one of the most common chart types and is helpful in visualizing the differences between discrete categories. Pygal's Bar chart allows you to plot data for different categories and add multiple series.
Syntax:
pygal.Bar(title=None, x_labels=None, style=None, width=None, height=None, legend_at_bottom=None)
- title: (str) The title of the chart.
- x_labels: (list) Labels for the x-axis, usually categories.
- style: (object) Optional styling for the chart (e.g., color themes).
- width: (int) Width of the chart in pixels.
- height: (int) Height of the chart in pixels.
- legend_at_bottom: (bool) Whether to place the legend at the bottom.
Python
import pygal
bar_chart = pygal.Bar()
bar_chart.add('Category A', [1, 3, 5, 7])
bar_chart.add('Category B', [2, 4, 6, 8])
bar_chart.render_to_file('bar_chart.svg')
Output:
Bar Chart2. Line Charts
Line charts are used to display information as a series of data points connected by straight lines. They are particularly useful for showing trends over time.
Syntax:
pygal.Line(title=None, x_labels=None, style=None, width=None, height=None, legend_at_bottom=None)
- title: (str) The title of the chart.
- x_labels: (list) Labels for the x-axis, often representing time intervals.
- style: (object) Optional chart styling.
- width: (int) Width of the chart.
- height: (int) Height of the chart.
- legend_at_bottom: (bool) Whether to display the legend at the bottom.
Python
import pygal
line_chart = pygal.Line()
line_chart.add('Series 1', [1, 3, 5, 7])
line_chart.add('Series 2', [2, 4, 6, 8])
line_chart.render_to_file('line_chart.svg')
Output:
Line Chart3. Pie Charts
Pie charts show data in a circle, with each slice representing a part of the whole. The size of each slice shows how much each category contributes. They're useful for displaying how different parts make up a total.
Syntax:
pygal.Pie(title=None, inner_radius=None, style=None, width=None, height=None)
- title: (str) The title of the chart.
- inner_radius: (float) Radius for the inner part of the pie (used in donut charts).
- style: (object) Optional styling.
- width: (int) Chart width.
- height: (int) Chart height.
Python
import pygal
pie_chart = pygal.Pie()
pie_chart.add('Part A', 10)
pie_chart.add('Part B', 20)
pie_chart.add('Part C', 30)
pie_chart.render_to_file('pie_chart.svg')
Output:
Pie Chart4. Donut Chart
A donut chart is a variation of the pie chart with a hole in the center. It’s useful when comparing proportions with some central data or reference point.
Syntax:
pygal.Pie(title=None, inner_radius=0.4, style=None, width=None, height=None)
- title: (str) The title of the chart.
- inner_radius: (float) Radius of the center hole (0.4 for a typical donut chart).
- style: (object) Optional style.
- width: (int) Chart width.
- height: (int) Chart height.
Python
import pygal
pie_chart = pygal.Pie(inner_radius=0.4)
pie_chart.add('Part A', 10)
pie_chart.add('Part B', 20)
pie_chart.add('Part C', 30)
pie_chart.render_to_file('donut_chart.svg')
Output:
Donut Chart5. Radar Charts
Radar charts display multivariate data on axes starting from the same point. They are good for comparing multiple variables.
Syntax:
pygal.Radar(title=None, x_labels=None, style=None, width=None, height=None)
- title: (str) The title of the chart.
- x_labels: (list) Labels for the radar axes, representing different variables.
- style: (object) Chart styling.
- width: (int) Chart width.
- height: (int) Chart height.
Python
import pygal
radar_chart = pygal.Radar()
radar_chart.add('Series 1', [1, 2, 3, 4])
radar_chart.add('Series 2', [4, 3, 2, 1])
radar_chart.render_to_file('radar_chart.svg')
Output:
Radar chart6. Histogram
Histograms show the distribution of numerical data by grouping data into bins and showing the frequency of data points within each bin.
Syntax:
pygal.Histogram(title=None, bins=None, style=None, width=None, height=None)
- title: (str) The title of the chart.
- bins: (list of tuples) Each tuple represents a bin with the format
(frequency, lower_bound, upper_bound)
. - style: (object) Chart style.
- width: (int) Chart width.
- height: (int) Chart height.
Python
import pygal
histogram = pygal.Histogram()
histogram.add('Data', [(0, 1), (5, 2), (10, 3)])
histogram.render_to_file('histogram.svg')
Output:
Histogram7. Box Plot
Box plots are used to display the distribution of data based on five summary statistics: minimum, first quartile, median, third quartile, and maximum.
Syntax:
pygal.Box(title=None, x_labels=None, style=None, width=None, height=None)
- title: (str) The title of the chart.
- x_labels: (list) Labels for the data categories.
- style: (object) Chart style.
- width: (int) Chart width.
- height: (int) Chart height.
Python
import pygal
box_plot = pygal.Box()
box_plot.add('Data', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
box_plot.render_to_file('box_plot.svg')
Output:
Box Plot8. XY Plot
XY plots (scatter plots) are used to plot two-dimensional data, showing the relationship between two variables. They help visualize patterns, trends, and correlations in the data, making it easier to understand how the variables interact.
Syntax:
pygal.XY(title=None, x_title=None, y_title=None, dots_size=None, style=None, width=None, height=None)
- title: (str) The title of the chart.
- x_title: (str) The label for the x-axis.
- y_title: (str) The label for the y-axis.
- dots_size: (int) Size of the dots representing data points.
- style: (object) Chart style.
- width: (int) Chart width.
- height: (int) Chart height.
Python
import pygal
xy_plot = pygal.XY(stroke=True)
xy_plot.add('Data', [(1, 2), (3, 4), (5, 6)])
xy_plot.render_to_file('xy_plot.svg')
Output:
XY PlotChart Customizations in Pygal
Pygal offers extensive customization options for charts. Customization is one of Pygal's standout features, allowing you to create personalized and visually appealing charts with minimal effort. From adjusting titles and labels to modifying colors, legends, and tooltips, Pygal provides extensive options to enhance your data visualizations. Here’s an in-depth look at the most important customization aspects:
1. Title and Labels
You can easily set titles and axis labels to make your chart more informative. Titles help provide context for the data being visualized, while labels guide the viewer in interpreting the data points.
- Title: Sets the title of the chart, displayed at the top.
- X and Y Labels: Define the labels for the x-axis and y-axis, typically representing categories and numerical values, respectively.
Python
import pygal
bar_chart = pygal.Bar(title='Bar Chart Title', x_label_rotation=30)
bar_chart.add('Category A', [1, 3, 5, 7])
bar_chart.add('Category B', [2, 4, 6, 8])
bar_chart.render_to_file('bar_chart.svg')
Output:
Chart Customizations in Pygal2. Colors and Styles
Pygal allows you to customize the color palette and overall style of your charts, ensuring they align with your branding or aesthetic preferences.
- Colors: You can assign specific colors to each data series, making charts more readable and visually distinct.
- Styles: Predefined styles like
LightStyle
and DarkStyle
are available, offering quick theming options, while you can also create custom styles by defining attributes such as background color, font size, and stroke width.
Python
import pygal
from pygal.style import Style
custom_style = Style(
colors=['#E80080', '#404040'],
background='#FFFFFF',
plot_background='#EFEFEF',
opacity='.6',
label_font_size=14,
)
bar_chart = pygal.Bar(style=custom_style)
bar_chart.add('Category A', [1, 3, 5, 7])
bar_chart.add('Category B', [2, 4, 6, 8])
bar_chart.render_to_file('bar_chart.svg')
Output:
Chart Customizations in Pygal3. Legends and Labels
Legends and labels provide additional information about the chart, such as explaining different series and categorizing data.
- Legends: The legend displays information about what each data series represents. You can position the legend at different locations, such as the bottom of the chart, for better layout control.
- Labels: Labels for individual data points can be displayed within the chart, showing exact values or categories for each bar, slice, or point.
Python
import pygal
line_chart = pygal.Line(legend_at_bottom=True)
line_chart.add('Series 1', [1, 3, 5, 7])
line_chart.add('Series 2', [2, 4, 6, 8])
line_chart.render_to_file('line_chart.svg')
Output:
Chart Customizations in PygalTooltips enhance interactivity by showing detailed information when the user hovers over a specific data point in the chart. This is especially useful for web-based visualizations where you want to provide more insight without cluttering the chart.
- Tooltips: Display additional data, such as exact values, categories, or even custom messages when hovering over chart elements.
- Interactive Charts: Enable dynamic updates of tooltips in SVG files embedded in web pages, adding a layer of interactivity to your visualizations.
Python
import pygal
pie_chart = pygal.Pie(tooltip_border_radius=10)
pie_chart.add('Part A', 10)
pie_chart.add('Part B', 20)
pie_chart.add('Part C', 30)
pie_chart.render_to_file('pie_chart.svg')
Output:
Chart Customizations in PygalFor more customizations, refer to:
Adding Multiple Series in Pygal
Adding multiple series to a chart in Pygal allows you to compare different datasets within the same visualization. This is particularly useful for spotting trends, patterns, and relationships between groups of data. Whether you’re comparing sales over different years, tracking multiple product categories, or analyzing performance metrics across departments, multiple series enhance the depth of your data representation.
Python
import pygal
bar_chart = pygal.Bar()
bar_chart.add('Series 1', [1, 2, 3])
bar_chart.add('Series 2', [3, 2, 1])
bar_chart.render_to_file('bar_chart.svg')
Output:
Adding Multiple Series in PygalCreating Dynamic Charts with Pygal
One of Pygal’s most powerful features is its ability to generate dynamic charts by integrating it with Python’s data structures. This means you can create charts that update automatically based on real-time or changing datasets, making Pygal an excellent choice for dashboards, reports, and web applications where data is continuously updated.
How Dynamic Charts Work:
- Python Data Structures: Pygal works with Python lists, dictionaries, and other iterable structures, allowing you to feed dynamic data directly into your charts. This enables real-time updates as your data changes, whether it's from a live data feed or periodic calculations.
- Flexibility: You can modify the data, adjust the chart parameters, and immediately render a new chart without manual intervention, providing a highly flexible and efficient workflow.
Example:
For instance, if you're tracking live sales data:
- Data Structure: A Python list or dictionary continuously updated with sales figures (
[500, 600, 700]
). - Dynamic Chart: Pygal will update the Bar chart automatically each time the data is modified, ensuring that your visualizations are always up-to-date.
Python
import pygal
data = {'Cats': [1, 2, 3], 'Dogs': [4, 5, 6]}
bar_chart = pygal.Bar()
for key, values in data.items():
bar_chart.add(key, values)
bar_chart.render_to_file('bar_chart.svg')
Output:
Dynamic Charts with PygalUse Case:
In a real-time dashboard, you might use a list of temperatures updated every minute. As the list is updated, Pygal dynamically reflects these changes in the Line chart, allowing for continuous monitoring of temperature trends.
Exporting and Embedding Charts in Pygal
One of Pygal’s strengths is that it can export charts as SVG files, which stay clear and sharp at any size. Pygal charts can be easily added to websites, making it simple to share interactive data online.
File Export Options:
- You can export your charts to different formats, including SVG and PNG, depending on your needs. SVG is ideal for web use, while PNG might be more suited for static presentations and reports.
Embedding Charts in Web Pages:
- HTML Integration: Embedding Pygal charts into HTML is simple. By rendering the chart as SVG, you can directly insert the SVG code into your web pages, or reference the saved SVG file using an HTML
<img>
tag. - Interactive Features: When embedded in a web page, Pygal charts retain their interactive features such as tooltips and hover effects.
To use Pygal charts in HTML, we use the render method to get the SVG data:
Python
import pygal
bar_chart = pygal.Bar()
bar_chart.add('Cats', [1, 2, 3])
svg_data = bar_chart.render()
with open('chart.html', 'w') as file:
file.write(f'<html><body>{svg_data}</body></html>')
In Conclusion Pygal is a powerful tool for creating SVG charts in Python. With its variety of chart types, extensive customization options, and advanced features, it offers flexibility for visualizing data in various ways.
Similar Reads
Data Visualization with Python
In today's world, a lot of data is being generated on a daily basis. And sometimes to analyze this data for certain trends, patterns may become difficult if the data is in its raw format. To overcome this data visualization comes into play. Data visualization provides a good, organized pictorial rep
14 min read
Data Visualization with Seaborn - Python
Seaborn is a widely used Python library used for creating statistical data visualizations. It is built on the top of Matplotlib and designed to work with Pandas, it helps in the process of making complex plots with fewer lines of code. It specializes in visualizing data distributions, relationships
9 min read
Data Visualization with Seaborn Line Plot
Prerequisite: SeabornMatplotlib Presenting data graphically to emit some information is known as data visualization. It basically is an image to help a person interpret what the data represents and study it and its nature in detail. Dealing with large scale data row-wise is an extremely tedious tas
4 min read
Python - Data visualization tutorial
Data visualization is a crucial aspect of data analysis, helping to transform analyzed data into meaningful insights through graphical representations. This comprehensive tutorial will guide you through the fundamentals of data visualization using Python. We'll explore various libraries, including M
7 min read
Data Visualisation with Chartify
Chartify is an open-source data visualization library from Spotify that makes it easy for data analysts to create charts and graphs. Chartify is built on top of Bokeh, which is a very popular data visualization library. This article gives a brief introduction to this technology. Modules Needed Inst
4 min read
Data analysis and Visualization with Python
Python is widely used as a data analysis language due to its robust libraries and tools for managing data. Among these libraries is Pandas, which makes data exploration, manipulation, and analysis easier. we will use Pandas to analyse a dataset called Country-data.csv from Kaggle. While working with
4 min read
KDE Plot Visualization with Pandas and Seaborn
Kernel Density Estimate (KDE) plot, a visualization technique that offers a detailed view of the probability density of continuous variables. In this article, we will be using Iris Dataset and KDE Plot to visualize the insights of the dataset. What is KDE Plot?KDE Plot described as Kernel Density Es
4 min read
Exploring 3D Data Visualization with Mayavi in Python
Mayavi is an interactive 3D plotting library that can be used to visualize complex spatial datasets. Although matplotlib can also be used for simple 3D plotting, Mayavi uses a more complex engine (VTK), making Mayavi more suitable for displaying large and complex data. The Mayavi library is like a m
7 min read
Logarithmic Scaling in Data Visualization with Seaborn
A wide range of libraires like Seaborn built on top of Matplotlib offers informative and attractive statistical graphics. However, the ability to scale axes is considered one of the essential features in data visualization, particularly when dealing with datasets that span multiple orders of magnitu
4 min read
Data Visualization in jupyter notebook
In this article, we will learn how to visualize data in Jupyter Notebook there are different libraries available in Python for data visualization like Matplotlib, seaborn, Plotly, GGPlot, Bokeh, etc. But in this article, we will use different libraries like Matplotlib, searborn, and Plotly which are
7 min read