Data Science
Matplotlib professional layouts, annotations and export
Compose consistent multi-panel reports, annotate findings and export a reproducible chart pack.
What you will learn
Compose consistent multi-panel reports, annotate findings and export a reproducible chart pack.
Before you start
You need basic variables, lists and function calls, not advanced Python algorithms. If these are new, visit Python foundations first.
- Create a local environment:
python -m venv .venv. Activate it for your OS and installpython -m pip install jupyterlab numpy pandas matplotlib seaborn plotly. - Download the 12-row sales CSV into your notebook folder. Keep its filename unchanged.
- Start Jupyter with
jupyter lab. Run the setup below in a fresh notebook before every workshop.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
raw = pd.read_csv('data-science-sales.csv', parse_dates=['date'])
df = raw.copy()
df['revenue'] = df['units'] * df['unit_price']
net = df.loc[df['returned'].eq(0)].copy()
Data dictionary: each row is one order for one product; units is a positive count; unit_price is INR per unit; returned is 0 or 1. Revenue is units × unit_price. For this workshop, net sales exclude the entire returned order (not partial returns). The CSV has 12 rows, 4950 gross revenue, 4450 net revenue and 35 net units. This small fictional sample teaches technique; it does not justify population or causal claims.
Save your notebook and written interpretation. There is no browser code judge and no automatic grading of visual design.
Official Matplotlib documentation
Learn the idea
A dashboard must answer a small set of questions rather than fit every possible chart. Use a shared definition of revenue across panels. fig.subplots or plt.subplots builds a grid of Axes; do not accidentally plot onto the wrong active axes. constrained_layout helps avoid overlapping labels. Export raster PNG for convenient sharing and vector SVG for scalable artwork. Put the date range and metric definition in the report itself, and close figures in batch scripts.
Follow a worked example
fig,axes=plt.subplots(1,2,figsize=(10,4),layout='constrained')
r=net.groupby('region')['revenue'].sum(); axes[0].bar(r.index,r.values)
p=net.groupby('product')['revenue'].sum(); axes[1].barh(p.index,p.values)
axes[0].set(title='Region',ylabel='INR'); axes[1].set(title='Product',xlabel='INR')
fig.suptitle('Q1 2026 net sales — full-order returns excluded')
fig.savefig('sales-report.svg'); plt.close(fig)
Expected result
Two panels sharing the same 4450 INR total, saved as sales-report.svg.
Skill-development workshop
These are practical assignments, not MCQs or code-judge puzzles. Work in your own notebook or MySQL client. Complete the levels in order; if a task feels difficult, follow the hint and compare with the reference only after making an attempt. Keep your result and a short explanation of what it means.
Easy: Set a reusable chart style without editing global settings permanently.
Success criteria: Style only applies inside the context; title and labels remain readable.
Need a starting point? Show the hint
Use plt.rc_context with a font.size setting.
Reference solution — open after trying
with plt.rc_context({'font.size':12}):
fig,ax=plt.subplots(); ax.plot([1,2,3],[1100,1550,1800],marker='o'); ax.set(xlabel='Month number',ylabel='INR',title='Monthly net revenue'); fig.tight_layout(); plt.close(fig)
Medium: Annotate the highest-revenue month.
Success criteria: March 1800 highlighted with text; arrow does not obscure the point.
Need a starting point? Show the hint
Use ax.annotate with offset points for text placement.
Reference solution — open after trying
fig,ax=plt.subplots(); ax.plot([1,2,3],[1100,1550,1800],marker='o')
ax.annotate('March: INR 1800',xy=(3,1800),xytext=(-100,-30),textcoords='offset points',arrowprops={'arrowstyle':'->'})
ax.set(xlabel='Month number',ylabel='Net revenue (INR)'); fig.tight_layout(); plt.show()
Hard: Build a two-panel monthly revenue and units report.
Success criteria: Revenue and units use separate labelled axes, not an unexplained dual axis; totals reconcile to net data.
Need a starting point? Show the hint
Use a 2×1 subplot grid and group both metrics together.
Reference solution — open after trying
m=net.groupby(net['date'].dt.to_period('M')).agg(revenue=('revenue','sum'),units=('units','sum'))
fig,axes=plt.subplots(2,1,figsize=(7,6),layout='constrained')
axes[0].plot(m.index.astype(str),m['revenue'],marker='o'); axes[0].set_ylabel('INR')
axes[1].bar(m.index.astype(str),m['units']); axes[1].set_ylabel('Units')
fig.suptitle('Monthly net sales'); plt.show()
Professional: Export a repeatable chart pack.
Success criteria: Both PNG and SVG exist, data export accompanies them, all figures closed and metric definition recorded.
Need a starting point? Show the hint
Use the same Figure object for both exports; no screenshot cropping.
Reference solution — open after trying
s=net.groupby('product')['revenue'].sum()
fig,ax=plt.subplots(figsize=(7,4),layout='constrained'); ax.barh(s.index,s.values); ax.set(xlabel='Net revenue (INR)',title='Q1 2026 product sales; returns excluded')
for ext in ['png','svg']: fig.savefig('product-report.'+ext,dpi=150)
plt.close(fig); s.rename('net_revenue_inr').to_csv('product-report.csv')
Reflection and submission
Save your queries/notebook and outputs. Write three sentences: what you changed, how you checked it, and one limitation. A correct chart or query without a clear interpretation is not a completed professional assignment.
fig,axes=plt.subplots(1,2,figsize=(10,4),layout='constrained')
r=net.groupby('region')['revenue'].sum(); axes[0].bar(r.index,r.values)
p=net.groupby('product')['revenue'].sum(); axes[1].barh(p.index,p.values)
axes[0].set(title='Region',ylabel='INR'); axes[1].set(title='Product',xlabel='INR')
fig.suptitle('Q1 2026 net sales — full-order returns excluded')
fig.savefig('sales-report.svg'); plt.close(fig)Lesson Code (python)
fig,axes=plt.subplots(1,2,figsize=(10,4),layout='constrained')
r=net.groupby('region')['revenue'].sum(); axes[0].bar(r.index,r.values)
p=net.groupby('product')['revenue'].sum(); axes[1].barh(p.index,p.values)
axes[0].set(title='Region',ylabel='INR'); axes[1].set(title='Product',xlabel='INR')
fig.suptitle('Q1 2026 net sales — full-order returns excluded')
fig.savefig('sales-report.svg'); plt.close(fig)Console Output
Two panels sharing the same 4450 INR total, saved as sales-report.svg.Up next · Continue learning
distributions and category comparisons
Use tidy DataFrames with histplot, scatterplot and boxplot while distinguishing transactions from aggregates.