PROGRAMMER'S PICNIC · PYTHON 0 TO INFINITY

Matplotlib: From Real Zero to Infinity

Never drawn a graph? Perfect. We begin with one dot, learn what a coordinate means, and gradually build scientific plots, dashboards, and data stories. Champuter teaches; you experiment in our Python Super Editor.

Start at real zeroOpen Python EditorExplore all levels

Before you write a single line

Matplotlib is a Python plotting library. Think of graph paper: the horizontal direction is called x, the vertical direction y. The point (2, 3) means move 2 units across and 3 units up. A line chart connects points, a bar chart compares categories, and a scatter plot displays individual observations.

Learning routine: Predict → Run → Observe → Change one thing → Run again → Explain. Every example is complete and starts with its own imports. Click Run in Editor to preload code, then press Run inside our editor. Click Visualize with Champuter and use the editor's Visualize mode for the real runtime demonstration. Your browser editor must support Matplotlib for charts to appear; the course page itself does not execute Python.

What you need: Basic typing and curiosity. Levels 0–4 introduce the minimum Python syntax as it arises. Some advanced examples need NumPy and Pandas, which may require a Python environment with those packages installed.

LEVEL 0

What is a graph?

A graph is a visual way to show information. A point has an x-coordinate (across) and a y-coordinate (up). Start with one dot: (2, 3).

Python · runnable example
import matplotlib.pyplot as plt

plt.plot(2, 3, marker='o')
plt.xlim(0, 5)
plt.ylim(0, 5)
plt.grid(True)
plt.show()
Try it yourself: Change the point to (4, 1). Predict where it will move.
LEVEL 1

Python, library, import, and pyplot

Python runs instructions. A library is reusable code. Matplotlib draws figures; pyplot is its convenient drawing interface. We give pyplot the short name plt.

Python · runnable example
import matplotlib.pyplot as plt

print('Matplotlib is ready')
plt.plot([1, 2, 3])
plt.show()
Try it yourself: Explain what import, as, plt and show mean in your own words.
LEVEL 2

Your first line: x and y

The first list contains horizontal coordinates; the second contains vertical coordinates. Pair equal positions: (1,2), (2,4), (3,6). Connecting those points makes a line.

Python · runnable example
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [2, 4, 6]
plt.plot(x, y)
plt.show()
Try it yourself: Add a fourth point (4, 8). What happens if the lists have different lengths?
LEVEL 3

Figure, axes, labels, title

A figure is the whole drawing. Axes are the plot area and scales. Labels explain units; titles tell the story.

Python · runnable example
import matplotlib.pyplot as plt

days = [1, 2, 3, 4]
visitors = [12, 18, 16, 25]
plt.plot(days, visitors, marker='o')
plt.title('Visitors by Day')
plt.xlabel('Day')
plt.ylabel('Visitors')
plt.grid(True)
plt.show()
Try it yourself: Change the title, the axis labels and the numbers.
LEVEL 4

Colour, markers, line style, legend

Visual encoding tells readers what a line represents. Colour distinguishes series; markers show measured points; a legend identifies each series.

Python · runnable example
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
plt.plot(x, [2, 4, 3, 6], color='royalblue', marker='o', linestyle='-', label='Shop A')
plt.plot(x, [1, 3, 5, 4], color='tomato', marker='s', linestyle='--', label='Shop B')
plt.legend()
plt.show()
Try it yourself: Change the markers and make a dotted second line.
LEVEL 5

Bar charts for categories

Use bars to compare amounts for different named categories, not to imply continuous movement.

Python · runnable example
import matplotlib.pyplot as plt

fruits = ['Apple', 'Mango', 'Orange']
sales = [20, 35, 14]
plt.bar(fruits, sales)
plt.title('Fruit Sales')
plt.ylabel('Units')
plt.show()
Try it yourself: Add a banana category and compare the highest and lowest values.
LEVEL 6

Horizontal bars and sorting

Horizontal bars are useful when category labels are long. Sort data before graphing to make rankings easy to read.

Python · runnable example
import matplotlib.pyplot as plt

items = ['Rice', 'Oil', 'Flour']
amounts = [40, 25, 35]
pairs = sorted(zip(amounts, items))
plt.barh([name for value, name in pairs], [value for value, name in pairs])
plt.xlabel('Quantity')
plt.show()
Try it yourself: Sort the same data in descending order instead.
LEVEL 7

Scatter plots and relationships

A scatter plot shows two measurements for each observation. A rising pattern suggests an association, not necessarily causation.

Python · runnable example
import matplotlib.pyplot as plt

hours = [1, 2, 2.5, 3, 4, 5]
marks = [30, 40, 43, 54, 67, 75]
plt.scatter(hours, marks)
plt.xlabel('Study hours')
plt.ylabel('Marks')
plt.show()
Try it yourself: Add two students. Can you spot an unusual point?
LEVEL 8

Histograms and distributions

Histograms group numerical measurements into intervals called bins. Unlike bar charts, adjacent bins represent a numerical range.

Python · runnable example
import matplotlib.pyplot as plt

marks = [25, 35, 38, 41, 48, 51, 55, 58, 63, 67, 72, 76, 81, 88]
plt.hist(marks, bins=[20, 40, 60, 80, 100], edgecolor='black')
plt.xlabel('Marks')
plt.ylabel('Student count')
plt.show()
Try it yourself: Use 2 bins and then 8 bins. Describe how the story changes.
LEVEL 9

Pie charts: parts of a whole

A pie chart is useful only when positive parts add up to one meaningful whole. Avoid it for too many categories.

Python · runnable example
import matplotlib.pyplot as plt

labels = ['Food', 'Travel', 'Books']
spending = [50, 30, 20]
plt.pie(spending, labels=labels, autopct='%1.0f%%')
plt.axis('equal')
plt.show()
Try it yourself: Explain why a bar chart may be easier for precise comparison.
LEVEL 10

Subplots and object-oriented plotting

Figure and Axes objects offer precise control. fig, ax = plt.subplots() is the foundation for reusable charts and dashboards.

Python · runnable example
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2, figsize=(9, 4))
axes[0].plot([1, 2, 3], [2, 4, 3])
axes[0].set_title('Trend')
axes[1].bar(['A', 'B', 'C'], [3, 5, 2])
axes[1].set_title('Comparison')
fig.tight_layout()
plt.show()
Try it yourself: Make a 2-by-2 layout and draw four charts.
LEVEL 11

Ticks, limits, annotations and grid

Good scales prevent misleading comparisons. Annotations call attention to meaningful events.

Python · runnable example
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 18, 14, 26], marker='o')
ax.set(xticks=[1, 2, 3, 4], ylim=(0, 30), title='Weekly progress')
ax.annotate('Best', xy=(4, 26), xytext=(2.7, 28), arrowprops={'arrowstyle':'->'})
ax.grid(alpha=0.3)
plt.show()
Try it yourself: Try truncating the y-axis. Discuss how it changes perception.
LEVEL 12

Error bars and uncertainty

Data often come from measurements or samples. Error bars communicate a range, but the meaning of that range must be stated.

Python · runnable example
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
mean = [5, 7, 6, 9]
uncertainty = [0.5, 0.8, 0.6, 1.1]
plt.errorbar(x, mean, yerr=uncertainty, fmt='o-', capsize=4)
plt.title('Mean with measurement uncertainty')
plt.show()
Try it yourself: Find the lower and upper bound for the fourth measurement.
LEVEL 13

Box plots and outliers

Box plots summarize the median, quartiles, spread and potential outliers of one or more numerical samples.

Python · runnable example
import matplotlib.pyplot as plt

class_a = [42, 50, 55, 60, 62, 66, 80]
class_b = [36, 48, 53, 57, 64, 73, 91]
plt.boxplot([class_a, class_b], tick_labels=['A', 'B'])
plt.ylabel('Marks')
plt.show()
Try it yourself: Which group has a higher median? Confirm from sorted data.
LEVEL 14

Functions, reusable styles and saving

Wrap plotting in functions, use consistent styling and save images with tight bounding boxes. In a browser editor, local file saving may differ from desktop Python.

Python · runnable example
import matplotlib.pyplot as plt

def draw_sales(names, values):
    fig, ax = plt.subplots(figsize=(7, 4))
    ax.bar(names, values, color='steelblue')
    ax.set(title='Shop Sales', ylabel='Units sold')
    fig.tight_layout()
    return fig

fig = draw_sales(['Mon', 'Tue', 'Wed'], [12, 19, 15])
fig.savefig('shop-sales.png', dpi=150, bbox_inches='tight')
plt.show()
Try it yourself: Change the function to accept a custom chart title.
LEVEL 15

NumPy, curves and mathematics

NumPy creates arrays of numbers. Matplotlib turns mathematical functions into visible curves; sampling density affects smoothness.

Python · runnable example
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 200)
y = np.sin(x)
plt.plot(x, y)
plt.axhline(0, color='gray', linewidth=0.8)
plt.title('Sine wave')
plt.show()
Try it yourself: Plot cosine on the same axes and add a legend.
LEVEL 16

Pandas, dates and real-world CSV data

Pandas groups and cleans tables. Matplotlib presents the result. Start with an in-memory table so the first run does not depend on file upload.

Python · runnable example
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'Date':['2026-11-01','2026-11-02','2026-11-03'], 'Sales':[120, 180, 160]})
df['Date'] = pd.to_datetime(df['Date'])
fig, ax = plt.subplots()
ax.plot(df['Date'], df['Sales'], marker='o')
ax.set(title='Daily sales', ylabel='Sales')
fig.autofmt_xdate()
plt.show()
Try it yourself: Read a CSV with Date and Sales columns on a desktop Python installation.
LEVEL 17

Heatmaps and two-dimensional data

Heatmaps map numerical values to colours. Always include a colour bar and label the values or units.

Python · runnable example
import numpy as np
import matplotlib.pyplot as plt

values = np.array([[1, 3, 2], [4, 5, 1], [2, 4, 6]])
fig, ax = plt.subplots()
image = ax.imshow(values, cmap='Blues')
fig.colorbar(image, ax=ax, label='Score')
ax.set(title='Scores by group')
plt.show()
Try it yourself: Change the values and compare palettes.
LEVEL 18

Animations, 3D and the infinity track

Go further with animation, 3D axes, interactivity, accessibility, reproducibility, colour perception, scientific plots and publication-ready dashboards. Animation support differs between browser runtimes.

Python · runnable example
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3, 3, 100)
y = x ** 2
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set(title='The infinity track begins', xlabel='x', ylabel='x squared')
plt.show()
Try it yourself: Capstone: build a four-chart dashboard from a real dataset and explain your design decisions.

Capstone projects: from useful to extraordinary

  1. Daily temperature tracker: line plot with labels and annotations
  2. Student marks analyzer: sorted bars, histogram, box plot
  3. Grocery shop sales dashboard: categories, dates, and comparison
  4. Sports training progress tracker: trend and uncertainty
  5. Air quality investigation: scatter, rolling average, distribution
  6. Multi-page scientific report: reproducible figures and proper units

Remember: An attractive chart is not necessarily an honest chart. Always check the axes, sample size, units, missing observations, and whether your choice of scale changes the interpretation.

Champuter

Hello! Start at Level 0. I'll explain any example you choose.