Lesson 8 · Data visualisation in python
Introduction to Matplotlib: Creating and Customizing Line and Bar Plots in Python
Welcome! This lesson is for absolute beginners who want to learn how to make beautiful plots in Python using the Matplotlib library. We will start from the…
- CourseData visualisation in python
- Lesson8 of 34
- Video14 min
- FormatJupyter notebook · 16 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbIntroduction to Matplotlib: Line and Bar Plots#
Welcome! This lesson is for absolute beginners who want to learn how to make beautiful plots in Python using the Matplotlib library.
We will start from the very basics and end with a mini-project using real-world time series data.
By the end, you will be able to create line and bar charts confidently!
import warnings
warnings.filterwarnings("ignore")
# Import matplotlib for plotting
import matplotlib.pyplot as plt
# We will use pandas to handle datasets
import pandas as pd
What is a Plot?#
A plot is a picture that represents data. It helps people see patterns and trends instead of staring at numbers.
In Python, plots are made with libraries like Matplotlib. The two most common plot types are line plots and bar plots.
# A simple line plot
plt.plot([1, 2, 3, 4], [2, 4, 6, 8])
plt.title("My First Line Plot")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
# A simple bar plot
plt.bar(["A", "B", "C"], [10, 5, 8])
plt.title("Bar Plot Example")
plt.xlabel("Category")
plt.ylabel("Amount")
plt.show()
Why Plots Matter#
Plots make it easier to understand data and explain results to other people. A good plot can instantly show a trend that is hidden in a table of numbers.
Soon, you will use real data from the real world.
# Data setup
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/shampoo.csv"
shampoo = pd.read_csv(url)
print("Shape of dataset:", shampoo.shape)
print("First 5 rows:")
print(shampoo.head())
# Convert Month to datetime for easier plotting
shampoo['Month'] = pd.date_range(start='1901-01', periods=shampoo.shape[0], freq='M')
shampoo['Month'] = pd.to_datetime(shampoo['Month'])
shampoo = shampoo.rename(columns={shampoo.columns[1]: 'Sales'})
# First look: Shampoo sales as a line plot
plt.figure(figsize=(10,5))
plt.plot(shampoo['Month'], shampoo['Sales'], marker='o')
plt.title("Monthly Shampoo Sales (line plot)")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid(True)
plt.tight_layout()
plt.show()
# Make a bar plot of the same data
plt.figure(figsize=(10,5))
plt.bar(shampoo['Month'].dt.strftime('%b-%y'), shampoo['Sales'], color='skyblue')
plt.title("Shampoo Sales by Month (bar plot)")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Choosing Between Line and Bar Plots#
Line plots are great for showing trends over time. Bar plots are best for comparing single values or categories.
You can use both in the same project depending on what you want to show.
# Add more lines to one plot
plt.figure(figsize=(10,5))
plt.plot(shampoo['Month'], shampoo['Sales'], marker='o', label='Shampoo Sales')
plt.plot(shampoo['Month'], shampoo['Sales'].rolling(3).mean(), color='red', linestyle='--', label='3-Month Average')
plt.title("Monthly Shampoo Sales and 3-Month Average")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.tight_layout()
plt.show()
# Highlight the highest sales month
max_month = shampoo.loc[shampoo['Sales'].idxmax(), 'Month']
max_value = shampoo['Sales'].max()
plt.figure(figsize=(10,5))
plt.plot(shampoo['Month'], shampoo['Sales'], marker='o', label='Sales')
plt.scatter([max_month], [max_value], color='red', label='Max Sales', zorder=5, s=100)
plt.title("Highlighting the Month with Highest Shampoo Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.tight_layout()
plt.show()
# Handling errors: What if a column is missing?
try:
plt.plot(shampoo['NotAColumn'])
except Exception as e:
print("Error:", e)
# Save your plot as an image
plt.figure(figsize=(10,5))
plt.plot(shampoo['Month'], shampoo['Sales'])
plt.title("To Save: Shampoo Sales Plot")
plt.savefig("shampoo_sales_plot.png")
plt.close()
print("Plot saved to shampoo_sales_plot.png")
Customizing Colors and Styles#
Matplotlib lets you choose colors, markers, and line styles. Custom styles make a chart match your message or brand.
# Make a line plot with custom color and marker
plt.figure(figsize=(10,5))
plt.plot(shampoo['Month'], shampoo['Sales'], color='green', linestyle='-.', marker='s')
plt.title("Custom Style: Shampoo Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.tight_layout()
plt.show()
# Add value labels to bar chart
plt.figure(figsize=(10,5))
bars = plt.bar(shampoo['Month'].dt.strftime('%b-%y'), shampoo['Sales'], color='purple')
for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x() + bar.get_width() / 2, yval + 2, int(yval), ha='center', va='bottom')
plt.title("Shampoo Sales With Value Labels")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Interactive: Try your own data
your_values = input("Enter four sales numbers separated by spaces: ")
sales = [int(num) for num in your_values.strip().split()]
plt.figure(figsize=(8,5))
plt.plot(range(1, len(sales)+1), sales, marker='o')
plt.title("Your Custom Line Plot")
plt.xlabel("Month Number")
plt.ylabel("Sales")
plt.tight_layout()
plt.show()
Mini-Project: Compare Two Products#
Imagine you manage two product lines. Lets pretend shampoo sales are one, and you invent a second set of numbers as the other.
# Mini-project: Compare Shampoo and Conditioner sales
conditioner_sales = shampoo['Sales'] * 0.8 + 10
plt.figure(figsize=(10,5))
plt.plot(shampoo['Month'], shampoo['Sales'], marker='o', label='Shampoo Sales')
plt.plot(shampoo['Month'], conditioner_sales, marker='^', color='orange', label='Conditioner Sales')
plt.title("Sales Comparison: Shampoo vs Conditioner")
plt.xlabel("Month")
plt.ylabel("Units Sold")
plt.legend()
plt.tight_layout()
plt.show()
# Mini-project: Make a bar plot for both products
import numpy as np
months = shampoo['Month'].dt.strftime('%b-%y')
bar_width = 0.4
x = np.arange(len(months))
plt.figure(figsize=(12,6))
plt.bar(x-bar_width/2, shampoo['Sales'], width=bar_width, label='Shampoo', color='blue')
plt.bar(x+bar_width/2, conditioner_sales, width=bar_width, label='Conditioner', color='orange')
plt.xlabel("Month")
plt.ylabel("Units Sold")
plt.title("Product Sales: Shampoo vs Conditioner (Bar Chart)")
plt.xticks(x, months, rotation=45)
plt.legend()
plt.tight_layout()
plt.show()
Challenge: Your Turn!#
Try making your very own plot from scratch. Use random numbers or real data, change colors, add labels, and try both line and bar charts.
Experiment and do not be afraid of errors. Every mistake is a learning step!
Recap: What Have We Learned?#
- How to make line and bar plots in Python
- How to work with real data using pandas
- How to label and style your charts
- How to compare different trends and highlight results
You are ready to use Matplotlib in your next project!
Want More Free Lessons?#
Like and subscribe to our channel for more fun Python tutorials and step-by-step projects. Tell us in the comments what you want to learn next!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



