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.
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).
import matplotlib.pyplot as plt
plt.plot(2, 3, marker='o')
plt.xlim(0, 5)
plt.ylim(0, 5)
plt.grid(True)
plt.show()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.
import matplotlib.pyplot as plt
print('Matplotlib is ready')
plt.plot([1, 2, 3])
plt.show()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.
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [2, 4, 6]
plt.plot(x, y)
plt.show()Figure, axes, labels, title
A figure is the whole drawing. Axes are the plot area and scales. Labels explain units; titles tell the story.
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()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.
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()Bar charts for categories
Use bars to compare amounts for different named categories, not to imply continuous movement.
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()Horizontal bars and sorting
Horizontal bars are useful when category labels are long. Sort data before graphing to make rankings easy to read.
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()Scatter plots and relationships
A scatter plot shows two measurements for each observation. A rising pattern suggests an association, not necessarily causation.
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()Histograms and distributions
Histograms group numerical measurements into intervals called bins. Unlike bar charts, adjacent bins represent a numerical range.
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()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.
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()Subplots and object-oriented plotting
Figure and Axes objects offer precise control. fig, ax = plt.subplots() is the foundation for reusable charts and dashboards.
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()Ticks, limits, annotations and grid
Good scales prevent misleading comparisons. Annotations call attention to meaningful events.
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()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.
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()Box plots and outliers
Box plots summarize the median, quartiles, spread and potential outliers of one or more numerical samples.
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()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.
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()NumPy, curves and mathematics
NumPy creates arrays of numbers. Matplotlib turns mathematical functions into visible curves; sampling density affects smoothness.
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()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.
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()Heatmaps and two-dimensional data
Heatmaps map numerical values to colours. Always include a colour bar and label the values or units.
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()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.
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()Capstone projects: from useful to extraordinary
- Daily temperature tracker: line plot with labels and annotations
- Student marks analyzer: sorted bars, histogram, box plot
- Grocery shop sales dashboard: categories, dates, and comparison
- Sports training progress tracker: trend and uncertainty
- Air quality investigation: scatter, rolling average, distribution
- 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.