Data Science
Matplotlib foundations: figures, axes and honest charts
Create labelled bar, line and scatter charts using the explicit Figure/Axes API.
What you will learn
Create labelled bar, line and scatter charts using the explicit Figure/Axes API.
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 Figure is the canvas; an Axes is one plot. plt.subplots returns both. Use bars for category totals, lines for ordered time and scatter for relationships. A bar chart should normally start at zero so bar length reflects magnitude. Label the metric, unit and net-sales definition. Always aggregate before plotting a business total; plotting individual transactions is a different question. Save the figure before show() in portable scripts.
Follow a worked example
regional=net.groupby('region')['revenue'].sum().sort_values()
fig,ax=plt.subplots(figsize=(6,4))
ax.barh(regional.index,regional.values,color='#1d4ed8')
ax.set(xlabel='Net revenue (INR)',title='Regional net sales — returns excluded')
fig.tight_layout()
fig.savefig('regional-sales.png',dpi=150)
plt.show()
Expected result
A horizontal bar chart: West 1400, North 1350, South 1700, labelled in INR.
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: Plot net product revenue as bars.
Success criteria: Four labelled bars, INR y-axis, zero baseline; Lamp highest at 2400.
Need a starting point? Show the hint
Start from groupby product revenue, then use ax.bar.
Reference solution — open after trying
s=net.groupby('product')['revenue'].sum()
fig,ax=plt.subplots(figsize=(6,4)); ax.bar(s.index,s.values)
ax.set(ylabel='Net revenue (INR)',title='Net sales by product'); ax.set_ylim(bottom=0)
fig.tight_layout(); plt.show()
Medium: Plot monthly net sales as an ordered line.
Success criteria: Three points: 1100,1550,1800; dates sorted; markers and INR label.
Need a starting point? Show the hint
Group by period before converting labels to strings.
Reference solution — open after trying
s=net.groupby(net['date'].dt.to_period('M'))['revenue'].sum().sort_index()
fig,ax=plt.subplots(); ax.plot(s.index.astype(str),s.values,marker='o')
ax.set(xlabel='Month',ylabel='Net revenue (INR)',title='Monthly net sales'); fig.tight_layout(); plt.show()
Hard: Show units versus order revenue and explain the limitation.
Success criteria: 11 dots; both axes labelled; note that price differences confound a simple units/revenue interpretation.
Need a starting point? Show the hint
Plot one point per net order; do not infer causation.
Reference solution — open after trying
fig,ax=plt.subplots(); ax.scatter(net['units'],net['revenue'])
ax.set(xlabel='Units per order',ylabel='Order revenue (INR)',title='Order size and revenue'); fig.tight_layout(); plt.show()
print('Higher units do not necessarily imply higher revenue: product prices differ.')
Professional: Deliver an accessible chart with a text alternative.
Success criteria: PNG saved; exact values also exported to CSV; one limitation sentence; no reliance on colour alone.
Need a starting point? Show the hint
Add direct value labels with bar_label, then export the source series.
Reference solution — open after trying
s=net.groupby('region')['revenue'].sum().sort_values()
fig,ax=plt.subplots(figsize=(6,4)); bars=ax.barh(s.index,s.values,color='#1d4ed8'); ax.bar_label(bars,padding=3)
ax.set(xlabel='Net revenue (INR)',title='Net sales by region; returns excluded'); ax.margins(x=0.2)
fig.tight_layout(); fig.savefig('regional-accessible.png',dpi=150); plt.close(fig)
s.rename('net_revenue_inr').to_csv('regional-accessible.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.
regional=net.groupby('region')['revenue'].sum().sort_values()
fig,ax=plt.subplots(figsize=(6,4))
ax.barh(regional.index,regional.values,color='#1d4ed8')
ax.set(xlabel='Net revenue (INR)',title='Regional net sales — returns excluded')
fig.tight_layout()
fig.savefig('regional-sales.png',dpi=150)
plt.show()Lesson Code (python)
regional=net.groupby('region')['revenue'].sum().sort_values()
fig,ax=plt.subplots(figsize=(6,4))
ax.barh(regional.index,regional.values,color='#1d4ed8')
ax.set(xlabel='Net revenue (INR)',title='Regional net sales — returns excluded')
fig.tight_layout()
fig.savefig('regional-sales.png',dpi=150)
plt.show()Console Output
A horizontal bar chart: West 1400, North 1350, South 1700, labelled in INR.Up next · Continue learning
Matplotlib professional layouts, annotations and export
Compose consistent multi-panel reports, annotate findings and export a reproducible chart pack.