Comprehensive Guide to ETL with PyGramETL and Data Visualization with Matplotlib
Overview and Architecture of PyGramETL
Institutional Framework and Platform Details:
- Academic Session: Data Warehouse Course Session, Academic Year (AU) 2025–2026.
- Institution: Ministère de l'Enseignement Supérieur et de Recherche Scientifique, Université de Sousse, École d'Ingénieurs & d'Architecture Polytechnique Sousse.
- Course Instructor: MR Kamel Garrouch.
- Official Website:
https://pygrametl.org/.
Definition and Purpose:
- PyGramETL is a dedicated Python package designed for programming Extract-Transform-Load (ETL) pipelines within data warehousing architectures.
- It offers a programmatic alternative to graphical ETL software, providing high customizability, code maintainability, and direct integration with Python's standard library and data ecosystem.
Core Capabilities of the Package:
- Provides classes specifically engineered to populate star schema and snowflake schema structures (dimensions and fact tables).
- Supplies standardized abstraction classes to extract data seamlessly from heterogeneous sources (relational databases, CSV files, text feeds).
- Enables the declaration and structuring of defined "steps" within an ETL processing flow.
- Supplies built-in utility functions solving recurring ETL requirements, such as key generation, hashing, and caching.
Internal Package Modules:
datasources: Contains classes and iterators for accessing and ingesting records from diverse source systems.tables: Supplies abstract, high-level interfaces to interact with, look up, and populate dimension and fact tables in target databases.parallel: Provides execution utilities to parallelize ETL processing steps across threads or processes.JDBCConnectionWrapperandjythonmultiprocessing: Offers specialized integration layers when running ETL scripts in a Jython environment to access Java Database Connectivity (JDBC) drivers.aggregators: Specialized components that support in-memory and streaming data aggregation operations.steps: Modular constructs for chaining discrete operational stages in an end-to-end ETL workflow.FIFODict: A dictionary structure with a constrained maximum capacity where overflow items are evicted strictly according to First-In, First-Out (FIFO) ordering.
Installation and Environment Configuration
Installing PyGramETL:
- The package is installed via standard Python package indexing using
pip:bash pip install pygrametl - Package Distribution Specifics: Version 2.8 is distributed as a source archive
pygrametl-2.8.tar.gz(size: , transfer rate: ) and compiles to a built wheelpygramet1-2.8-py3-none-any.whl(size: , SHA256:a50688af308174d6287269505237f5b7622020434d099551071f731fc42529cb).
- The package is installed via standard Python package indexing using
Installing the PostgreSQL Driver (
psycopg2):psycopg2provides PEP 249-compliant connectivity between Python and PostgreSQL databases.- Method 1 (pip):
bash pip install psycopg2 # Or for pre-compiled standalone binaries without local C toolchain: pip install psycopg2-binary
Method 2 (Conda / Anaconda Prompt):
- Launch Anaconda Prompt.
- Execute:
bash conda install -c anaconda psycopg2
Importing Dependencies:
- ETL programs utilizing PostgreSQL and PyGramETL require importing both base packages:
python import psycopg2 import pygrametl
- ETL programs utilizing PostgreSQL and PyGramETL require importing both base packages:
Database Connectivity and Management via psycopg2
Session Instantiation:
The
psycopg2.connect()method initializes a database session and returns an active connection instance.Basic Connection Syntax: ```python import psycopg2 import pygrametl
pgconn = psycopg2.connect(dbname='DwhVente', user='postgres', password='system') print('connection établie') ```
Connection and Cursor Operational Lifecycle:
- Connection Object (
pgconn): Encapsulates the entire database session.- Creates cursor instances via
.cursor(). - Persists transaction changes permanently to the database storage engine using
.commit(). - Terminates database sessions using
.close().
- Creates cursor instances via
- Cursor Object (
cur): Handles SQL statement compilation and execution.- Sends commands to the database server via
.execute(query). - Retrieves query results via record extraction methods:
.fetchone(),.fetchmany(size), and.fetchall(). - Frees allocated server-side cursor resources using
.close().
- Sends commands to the database server via
- Connection Object (
Table Definition and Data Manipulation Implementation:
The following code sets the PostgreSQL schema search path to
schDwhVente, defines thepersonnetable, populates records, commits the transaction, and closes all handles: ```python import psycopg2 import pygrametlpgconn = psycopg2.connect( database='DwhVente', host="localhost", user='postgres', password='system' ) print(' ok connecté') cur = pgconn.cursor() cur.execute("set search_path to 'schDwhVente'") cur.execute("CREATE TABLE personne( id int, prenom varchar(50), nom varchar(50));")
Insertion de données
cur.execute("insert into personne( id , prenom , nom) values (5, 'Anis', 'Ben Salah');") cur.execute("insert into personne( id , prenom , nom) values (1, 'Ahmed', 'Ben Salah');") cur.execute("insert into personne( id , prenom , nom) values (2, 'Salah', 'Ben Ahmed');") cur.execute("insert into personne( id , prenom , nom) values (3, 'Karim', 'Salahi');") cur.execute("insert into personne( id , prenom , nom) values (4, 'Sadok', 'Sassi');")
pgconn.commit() cur.close() pgconn.close() ```
Reading and Fetching Rows:
Records are extracted using SQL queries and parsed into Python tuples via
.fetchall().PostgreSQL automatically establishes internal numeric indexing for table rows and fields: ```python import psycopg2 import pygrametl
pgconn = psycopg2.connect( database='DwhVente', host="localhost", user='postgres', password='system' ) cur = pgconn.cursor() cur.execute("set search_path to 'schDwhVente';") cur.execute('SELECT * FROM personne;') rows = cur.fetchall() cur.close()
for row in rows: print(row)
for row in rows: print('nom : ', row[2], ' ', 'prenom :', row[1]) ```
Record Updates and Deletions:
Updating Records: ```python import psycopg2 import pygrametl
pgconn = psycopg2.connect( database='DwhVente', host="localhost", user='postgres', password='system' ) cur = pgconn.cursor() cur.execute("set search_path to 'schDwhVente';") cur.execute("UPDATE personne SET prenom = 'Salah' WHERE id = 5;") pgconn.commit() pgconn.close() ```
Deleting Records:
python cur.execute("DELETE from personne WHERE id=5") Advanced SQL Queries Executed via Python:
- Sorting Records (
ORDER BY):python cur.execute("set search_path to 'schDwhVente';") cur.execute('SELECT * FROM personne ORDER BY prenom') rows = cur.fetchall() for row in rows: print(row) pgconn.commit() pgconn.close()
- Sorting Records (
Aggregations with Grouping (
GROUP BY):python cur.execute("set search_path to 'schDwhVente';") cur.execute('SELECT id_magasin, COUNT(*) FROM transactiontpv GROUP BY id_magasin') rows = cur.fetchall() for row in rows: print(row) pgconn.commit() pgconn.close() Relational Joins (
INNER JOINwith Aggregation across Tables):python pgconn = psycopg2.connect( database='DwhVente', host="localhost", user='postgres', password='system', port=5433 ) cur = pgconn.cursor() cur.execute(""" SELECT nom_magasion, sum(prix * nbArticle) FROM magasin INNER JOIN TransactionTPV ON magasin.id_magasin = TransactionTPV.id_magasin GROUP BY magasin.id_magasin, nom_magasion """) rows = cur.fetchall() for row in rows: print(row) pgconn.commit() pgconn.close() PyGramETL Connection Wrapper Abstraction:
PyGramETL provides a
ConnectionWrapperclass to wrap native PEP 249 database connection objects, automating transaction management and parameter handling across ETL components.Wrapper Initialization and Default Configuration: ```python import psycopg2 import pygrametl
pgconn = psycopg2.connect( database='DwhVente', host="localhost", user='postgres', password='system', port=5433 ) connection = pygrametl.ConnectionWrapper(pgconn) connection.setasdefault() connection.execute('set search_path to "schDwhVente"') pgconn.close() ```
Dimensional Modeling in PyGramETL
Specification Principles:
- Every dimension in the underlying warehouse star or snowflake schema must map to an instantiated PyGramETL abstraction object.
- Fact tables must likewise map to an instantiated
FactTableobject. - Target tables must already exist in the database schema prior to loading.
- An active database connection must be encapsulated as the default
ConnectionWrapper.
Defining
DimensionObjects:Instantiated using
from pygrametl.tables import Dimension.Required Constructor Parameters:
name: The exact table name in the relational database.key: The primary key attribute (often a surrogate key).attributes: A list of strings defining dimensional descriptive fields.
Implemented Dimensions in
DwhVente: ```pythonMagasin Dimension
Magasin_dimension = Dimension( name='Magasin', key='id_magasin', attributes=['nom', 'adresse'] )
Produit Dimension
Produit_dimension = Dimension( name='Produit', key='id_produit', attributes=['nom', 'desc_produit'] )
Promotion Dimension
promotion_dimension = Dimension( name='Promotion', key='id_promo', attributes=['pourcentage_remise'] )
Temps Dimension
Temps_dimension = Dimension( name='Temps', key='id_temps', attributes=['jour', 'semaine', 'mois', 'annee'] ) ```
Classes Derived from
Dimension:CachedDimension: Retains dimension entries in local memory to speed up key lookups and minimize repetitiveSELECTqueries.BulkDimension: Implements bulk data loading mechanisms for high-throughput batch ingestion.CachedBulkDimension: Combines in-memory key lookup caching with bulk insertion capabilities.TypeOneSlowlyChangingDimension: Automatically overwrites existing dimension attributes with new values (SCD Type 1 behavior).SlowlyChangingDimension: Manages historical tracking by versioning rows with validity timestamps or version flags (SCD Type 2 behavior).SnowflakedDimension: Manages normalized dimensional hierarchies that branch into multiple relational tables.
Defining
FactTableObjects:- Instantiated using
from pygrametl.tables import FactTable. - Required Constructor Parameters:
name: Target fact table name in the warehouse.keyrefs: A list of strings defining foreign keys referencing the dimensions.measures: A list of strings defining additive or non-additive numerical measures.
- Implemented Fact Table in
DwhVente:python fact_TransactionTPV = FactTable( name='TransactionTPV', keyrefs=['id_produit', 'id_magasin', 'id_temps', 'id_promo'], measures=['nbArticle', 'prix'] )
- Instantiated using
Classes Derived from
FactTable:BatchFactTable: Collects inserted facts into an internal memory buffer and executes database inserts in batches rather than individual transactions.BulkFactTable: Uses database-specific bulk insertion utilities (such as PostgreSQL'sCOPYcommand) to achieve maximum write performance.
Complete Schema Instantiation Script: ```python import psycopg2 import pygrametl from pygrametl.tables import Dimension, FactTable
pgconn = psycopg2.connect( database='DwhVente', host="localhost", user='postgres', password='system', port=5433 ) connection = pygrametl.ConnectionWrapper(pgconn) connection.setasdefault() connection.execute('set search_path to "schDwhVente"') print('connexion etablie') print('spécification des faits et des dimensions')
Magasin_dimension = Dimension(name='Magasin', key='id_magasin', attributes=['nom', 'adresse']) Produit_dimension = Dimension(name='Produit', key='id_produit', attributes=['nom', 'desc_produit']) promotion_dimension = Dimension(name='Promotion', key='id_promo', attributes=['pourcentage_remise']) Temps_dimension = Dimension(name='Temps', key='id_temps', attributes=['jour', 'semaine', 'mois', 'annee'])
fact_TransactionTPV = FactTable( name='TransactionTPV', keyrefs=['id_produit', 'id_magasin', 'id_temps', 'id_promo'], measures=['nbArticle', 'prix'] )
pgconn.close() ```
Data Extraction Mechanisms with PyGramETL
Data Representation Model:
- Data flowing through PyGramETL is represented as standard Python dictionaries, conventionally assigned to a variable named
row. - Keys in the dictionary represent column/attribute names, and values represent the associated record data.
- All data source abstractions in PyGramETL are Python iterables, allowing standard iteration:
python for row in datasource: # ETL processing steps
- Data flowing through PyGramETL is represented as standard Python dictionaries, conventionally assigned to a variable named
Relational Database Extraction via
SQLSource:- Extracts records from a PEP 249 database connection using arbitrary SQL statements.
- Requires a mapping of query column names via
names=name_mapping. - Constraint: The number of attributes specified in
name_mappingmust correspond precisely to the number of columns output by the query. - Syntax:
python name_mapping = ('champs1', 'champs2', 'champs3', 'champs4') sales_source = SQLSource( connection=nom_connection, query="SELECT * FROM table", names=name_mapping )
Flat File Extraction via
CSVSource:- Extracts tabular records from delimited text files without requiring database queries.
- Under the hood, PyGramETL uses Python's built-in
csv.DictReader, extracting field names from the file header. - File access is initiated using Python's
open()function, configuring an explicit buffer size (e.g., ):python fichierSource = open('nomfichier.csv', 'r', 16384) region_source = CSVSource(csvfile=fichierSource, delimiter=',')
Source Joining and Combination Strategies:
MergeJoiningSource:Performs a merge join on two independent data sources.
Prerequisite: Both input data sources must be pre-sorted in identical sort order on the join keys.
Syntax: ```python import pygrametl from pygrametl.datasources import CSVSource, MergeJoiningSource
products = CSVSource(csvfile=open('products.csv', 'r', 16384), delimiter=',') sales = CSVSource(csvfile=open('sales.txt', 'r', 16384), delimiter='\t') data = MergeJoiningSource(src1=products, key1='productID', src2=sales, key2='productID') ```
HashJoiningSource:Executes an in-memory hash join between two sources using an internal hash table (H-Map).
Advantage: Does not require either input data source to be pre-sorted.
Syntax: ```python import pygrametl from pygrametl.datasources import CSVSource, HashJoiningSource
products = CSVSource(csvfile=open('products.csv', 'r', 16384), delimiter=',') sales = CSVSource(csvfile=open('sales.txt', 'r', 16384), delimiter='\t') data = HashJoiningSource(src1=products, key1='productID', src2=sales, key2='productID')```
Alternative Source Joining Classes:
UnionSource: Computes the union of multiple data sources, emitting rows sequentially from each.RoundRobinSource: Interleaves rows from multiple input sources in an alternating round-robin distribution.ProcessSource: Encapsulates a process or external script as a streaming data source.CrossTabbingSource: Pivots incoming rows into cross-tabulated matrix structures.
Filtering Records via
FilteringSource:Applies a predicate filter to an incoming source stream.
Default Behavior: Eliminates empty rows using standard Python truth-value evaluations.
Custom Filtering: Accepts a callable function
f(row)returning a boolean (Trueto pass the record forward,Falseto discard): ```python import pygrametl from pygrametl.datasources import CSVSource, FilteringSourcedef locationfilter(row): if row['location'] == 'Aalborg': return True else: return False
sales = CSVSource(csvfile=open('sales.csv', 'r', 16384), delimiter='\t') sales_filtered = FilteringSource(source=sales, filter=locationfilter) ```
Data Transformation and Cleansing
- Core Objectives of the Transformation Phase:
- Standardization: Normalizing disparate vocabularies, structural encodings, character representations, and categorical domains.
- Deduplication: Identifying and merging redundant records originating across disjoint transactional sources.
- Cleansing: Identifying, correcting, or dropping corrupt, anomalous, or incomplete records.
- Reformatting: Aligning data types, schemas, and granularity with the target warehouse model.

Functional Row Transformations via
TransformingSource:TransformingSourceapplies one or more transformation functionsf(row)to each record in a stream in the exact sequence provided.Currency Conversion Example (Tunisian Dinar to Euro):
- The exchange conversion formula divides the price in Tunisian Dinars by : ```python import pygrametl from pygrametl.datasources import CSVSource, TransformingSource
def dinar_to_eur(row): prix_din = int(row['prix']) row['price'] = prix_din / 3.3
sales = CSVSource(csvfile=open('sales.csv', 'r', 16384), delimiter=',') sales_transformed = TransformingSource(source=sales, target=dinar_to_eur) ```
Custom Attribute Parsing Implementations:
- URL Domain Parsing Function: Extracts domain strings from full HTTP URLs (e.g., retrieving
'www.domain0.tl0'from'http://www.domain0.tl0/page0.html'):python def extractdomaininfo(row): domaininfo = row['url'].split('/')[-2] row['domain'] = domaininfo
- URL Domain Parsing Function: Extracts domain strings from full HTTP URLs (e.g., retrieving

- Calendar Date String Splitting Function: Decomposes delimited dates (
dd-mm-yyyyoryyyy-mm-dd) into separate year, month, and day components for dimensional assignment:python def split_timestamp(row): timestamp = row['timestamp'] timestamp_split = timestamp.split('-') row['year'] = timestamp_split[0] row['month'] = timestamp_split[1] row['day'] = timestamp_split[2]
Loading Strategies for Dimensions and Facts
Operational Considerations during the Load Phase:
- Calculation and Rollup: Computing complex metrics and aggregates prior to storage.
- Database Substitution: Replacing legacy databases or flat storage if direct extraction pipelines fail.
- Execution Scheduling: Scheduling heavy batch loads during off-peak operational windows (e.g., overnight batch runs).
- Restoration and Redundancy: Implementing automated rollback routines and redundant infrastructure to ensure high availability during loading cycles.
- Granularity Management: Retaining atomic, detailed transactional records while generating aggregated summaries for high-speed analytical queries.
Loading Dimensions:
- Dimension rows are typically iterated from sources and inserted via the
.insert(row)method on the dimension instance. - List Comprehension Ingestion:
python [location_dimension.insert(row) for row in region_source]
- Dimension rows are typically iterated from sources and inserted via the
Loading Fact Tables:
Direct Ingestion via
.insert(row): Appends new records directly into the physical fact table. ```python facts = [ {'storeid': 1, 'productid': 13, 'dateid': 4, 'price': 50}, {'storeid': 2, 'productid': 7, 'dateid': 4, 'price': 75}, {'storeid': 1, 'productid': 7, 'dateid': 4, 'price': 50}, {'storeid': 3, 'productid': 9, 'dateid': 4, 'price': 25} ]for row in facts: factTable.insert(row) conn.commit() ```
Key Lookup via
.lookup(): Verifies whether a fact record already exists in the target table based on its dimensional key combinations:python factTable.lookup({'storeid': 1, 'productid': 13, 'dateid': 4}) Conditional Ingestion via
.ensure(): Integrates lookup and insert logic. It verifies that a fact record does not already exist before inserting it.Method Signature:
factTable.ensure(row, compare_measures, name_mapping).Behavior of
compare_measures: If set toTrue, the method checks whether matching dimensional keys also contain identical measure values. If the keys match but the measure values differ, it raises aValueError.Behavior of
name_mapping: Accepts a dictionary mapping input row keys to database column names (e.g., mapping incoming'itemid'to the schema's'productid'). ```python newFacts = [ {'storeid': 2, 'itemid': 7, 'dateid': 4, 'price': 75}, {'storeid': 1, 'itemid': 7, 'dateid': 4, 'price': 50}, {'storeid': 1, 'itemid': 2, 'dateid': 7, 'price': 150}, {'storeid': 3, 'itemid': 3, 'dateid': 6, 'price': 100} ]for row in newFacts: factTable.ensure(row, True, {'productid': 'itemid'})
conn.commit() conn.close() ```
Case Study: Road Safety Data Warehouse
Project Context:
- Analysis of road accident occurrences conducted on behalf of an automotive insurance company.
- Objective: Build, model, and populate an analytical data warehouse from raw CSV operational data using PyGramETL.
Step-by-Step Implementation Procedure:
- Download course project resources from the classroom directory
tp application. - Open and review the dimensional schema document
schemaProjet-exempleSecuriteRoutière.pdf. - Create the designated warehouse schema, tables, dimensions, and facts inside a PostgreSQL database.
- In Jupyter Notebook, load the base ETL implementation code from
Script testé. - Refactor, test, and debug the script to complete a fully functional pipeline.
- Download course project resources from the classroom directory
Curriculum Bibliographic References:
- PyGramETL Beginner Documentation:
https://pygrametl.org/doc/quickstart/beginner.html. - Dr. Zahra KODI AAOUINA – Course Materials, ISG Tunis.
- Karima Tekaya – Informatique Décisionnelle, INSAT.
- Fatma Baklouti – Les entrepôts de données (Data Warehouses), INSAT.
- Didier Donsez – Conception de Bases Décisionnelles, Université Joseph Fourier.
- E. Grislin-Le Strugeon – Systèmes d'information décisionnels (Data Warehouse / Data Mining), Université de Valenciennes.
- PyGramETL Beginner Documentation:
Data Visualization with Matplotlib: Curves and Layouts
The
matplotlib.pyplotModule:- Provides functional plotting tools to manage figures, construct axes, customize plot styles, format lines, and add text and annotations.
Mechanics of
plt.plot():When passed a single list , the values are treated as the vertical ordinates (-axis). Abscissa coordinates (-axis) are automatically generated as integer indices ranging from to .
The command draws continuous segments connecting points , , and .
Linestyle Parameters:
'-': Solid line (default style).'--': Dashed line.':': Dotted line.'-.': Dash-dot line.
Basic Single-Curve Example: ```python import matplotlib.pyplot as plt
y = [1.0, 2.4, 1.7, 0.3, 0.6, 1.8] plt.plot(y) plt.title("Graphique") plt.show() ```

Plotting Multiple Routes on Single Axes:
Multiple datasets can be drawn on the same canvas by issuing sequential
plt.plot()calls before callingplt.show(): ```python import matplotlib.pyplot as pltx = [0, 1, 2] y = [0, 1.2, 2.6] x1 = [0, 2, 3] y1 = [2, 1.4, 0] x2 = [0, 1, 2] y2 = [0, 1, 2]
plt.plot(x, y) plt.plot(x1, y1) plt.plot(x2, y2) plt.title("Graphique") plt.show() ```

Plot Parameter Customizations:
title: Sets the chart title string viaplt.title(...).legend: Renders the chart legend viaplt.legend(), which must be placed prior toplt.show().label: Assigns an identifier label to a curve for legend rendering.color: Controls stroke color. Accepts full names or standard single-letter codes:'b': Blue'g': Green'r': Red'c': Cyan'm': Magenta'y': Yellow'k': Black'w': White
Trigonometric Multi-Curve Example: ```python import matplotlib.pyplot as plt import numpy as np
x = np.linspace(0, 10, 100) plt.plot(x, np.sin(x), '-b', label='Sine Wave') plt.plot(x, np.cos(x), '--r', label='Cosine Wave') plt.legend() plt.show() ```
Grid and Axis Formatting:
- Grid Activation via
plt.grid():axis: Restricts grid lines to'both'(default),'x', or'y'.color: Defines grid stroke color.linewidth: Sets stroke width.linestyle: Sets pattern ('-','--',':','-.').
- Axis Labels and Bounds:
plt.xlabel("text")andplt.ylabel("text")label the respective axes.plt.axis([xmin, xmax, ymin, ymax])sets explicit numeric boundaries.
- Grid Activation via
Managing Multiple Figures and Subplots:
plt.figure(number)initializes or switches focus between independent canvas windows.plt.subplot(nrows, ncols, plot_number)divides the active canvas into a grid of sub-axes.plt.savefig('filename.png')exports the figure to disk.Multi-Figure Workflow: ```python import matplotlib.pyplot as plt
plt.figure(1) # Select figure 1 plt.subplot(211) # Subplot 1 of figure 1 (top) plt.plot([1, 2.5, 3]) plt.subplot(212) # Subplot 2 of figure 1 (bottom) plt.plot([4, 2, 6]) plt.savefig('Firstfig.png') # Save figure 1
plt.figure(2) # Select figure 2 plt.plot([4, 5, 6]) # Default subplot(111)
plt.figure(1) # Return focus to figure 1 plt.subplot(211) # Reactivate top subplot of figure 1 plt.title('Multiple diagrams in the same figure') plt.show() ```
Worked Exercise 1: Trajectory Plot:
- Requirements:
- Plot Trajet 1: points , , , using a red dashed line (
"r--"), star markers (marker="*"), labeled"Trajet 1". - Plot Trajet 2: points , , , using blue square markers with line width (
"bs",linewidth=0.8), cross markers (marker="+'"), labeled"Trajet 2". - Assign title:
"Exercice 1-Courbe"(or"Graph in Python"). - Activate canvas grid.
- Set -axis label to
"Vitesse"(Speed) and -axis label to"Temps"(Time). - Render the legend.
- Plot Trajet 1: points , , , using a red dashed line (
- Requirements:

Statistical Visualizations: Histograms and Pie Charts
Histogram Generation via
plt.hist():Automatically categorizes raw, unaggregated numeric data into discrete bins and computes frequency distributions.
Method Signature:
n, bins, patches = plt.hist(x, bins, normed=1, facecolor='color', alpha=transparency).Uniform Distribution Simulation Example: ```python import matplotlib.pyplot as plt import random
L = [] for i in range(10000): a = random.random() L.append(a)
plt.hist(L, 20, normed=True) plt.show() ```
Worked Exercise 2: Discrete Random Histogram:
Requirements: Generate random integer draws between and , divide into bins, normalize frequency (
normed=1), apply blue fill (facecolor='b') with opacity (alpha=0.5), label -axis'Mise', -axis'Probabilité', enforce viewport bounds , and activate the grid.Implementation: ```python import matplotlib.pyplot as plt import random
x = [random.randint(0, 150) for i in range(1000)] n, bins, patches = plt.hist(x, 50, normed=1, facecolor='b', alpha=0.5) plt.xlabel('Mise') plt.ylabel('Probabilité') plt.axis([0, 150, 0, 0.02]) plt.grid(True) plt.show() ```
Pie Chart Generation via
plt.pie():- Complete Parameter Signature:
python pie( x, explode=None, labels=None, colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'), autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False ) - Core Parameters:
explode: A tuple/list specifying radial fractional offsets to separate wedges.autopct: A format string (e.g.,'%1.1f%%') displaying relative percentage values on wedges.startangle: Rotates the first wedge counter-clockwise by a specified angle in degrees.shadow: Boolean enabling a drop-shadow effect.
- Enforcing Circular Aspect Ratio:
- Calling
plt.axis('equal')ensures the pie chart remains perfectly circular rather than stretching into an ellipse to match container dimensions.
- Calling
- Complete Parameter Signature:
Worked Exercise 3: Age Demographic Pie Chart:
Dataset:
- Age Categories:
['-18', '18-25', '25-50', '50+'] - Frequencies:
[5000, 26000, 21400, 12000]
- Age Categories:
Requirements: Explode the
'18-25'segment by , format percentages to one decimal point, setstartangle=90, enable drop shadow, and enforce equal aspect ratio.Implementation: ```python import matplotlib.pyplot as plt
name = ['-18', '18-25', '25-50', '50+'] data = [5000, 26000, 21400, 12000] explode = (0, 0.15, 0, 0)
plt.pie( data, explode=explode, labels=name, autopct='%1.1f%%', startangle=90, shadow=True ) plt.axis('equal') plt.show() ```
Database-Driven Visualizations in Python
End-to-End Database Ingestion to Matplotlib Pipeline:
Combines
psycopg2data querying withmatplotlib.pyplotcurve plotting inside an integrated development environment (e.g., Spyder).Database Context: Target database
DWLivre, schema/table"DWLivre".Livre, target attributePrixLivre.Implementation Script: ```python import matplotlib.pyplot as plt import psycopg2
Connect to the PostgreSQL Data Warehouse
pgconn = psycopg2.connect( dbname='DWLivre', user='postgres', password='0000' ) cursor = pgconn.cursor()
Execute query against the Livre table
cursor.execute('""'"SELECT PrixLivre FROM "DWLivre".Livre"'"')
Ingest and unpack prices into a Python list
ListP = [] for prix in cursor: ListP.append(prix[0])
print(ListP)
Render the price curve
plt.plot(ListP) plt.show() ```