Lesson 12 · Python For Time Series
Data Visualization with Matplotlib
In this lesson, you will learn the basics of visualizing data using Python. No experience required. Let us explore how to make beautiful, useful charts step…
- CoursePython For Time Series
- Lesson12 of 30
- Video34 min
- FormatJupyter notebook · 20 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynb
Welcome to Data Visualization with Matplotlib!#
In this lesson, you will learn the basics of visualizing data using Python.
No experience required. Let us explore how to make beautiful, useful charts step by step.
We will use Matplotlib, a popular Python library for making plots.
import warnings
warnings.filterwarnings("ignore")
# This hides warnings so they do not distract us.
What is Matplotlib?#
Matplotlib is a toolkit that helps you make graphs and charts in Python. It is very popular because it is simple and flexible.
You can use Matplotlib to make line plots, bar charts, pie charts, and much more.
# Import Matplotlib and pyplot
import matplotlib.pyplot as plt
# 'plt' is a short name for pyplot, the main part of Matplotlib used for making plots.
# Our first plot: a simple line
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.title("A simple line plot")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.show()
Real-world data: Let us load a sample dataset!#
We will use a real dataset about monthly shampoo sales.
This will help you see how visualization works with real numbers.
import pandas as pd
# Data setup
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/shampoo.csv"
data = pd.read_csv(url)
print("Shape of the data:", data.shape)
print("First few rows:")
print(data.head())
# Let us plot the shampoo sales over time
plt.figure(figsize=(8, 4))
plt.plot(data["Month"], data["Sales"])
plt.title("Monthly Shampoo Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Customizing Plots#
You can change how your plots look by choosing colors, markers, line styles, and more. This helps you highlight important details or make your charts unique.
# A custom plot with markers and color
plt.plot(data["Month"], data["Sales"], color="green", marker="o", linestyle="--")
plt.title("Shampoo Sales with Custom Style")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Adding a legend
plt.plot(data["Month"], data["Sales"], color="purple", label="Shampoo Sales")
plt.title("Shampoo Sales with a Legend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Bar plot: comparing sales across months
plt.bar(data["Month"], data["Sales"], color="skyblue")
plt.title("Sales as a Bar Chart")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Handling Missing Data#
Real datasets sometimes have missing values. Let us check if our sales data has any gaps.
# Check for missing data
missing = data.isnull().sum()
print("Missing values per column:")
print(missing)
# Highlight the highest month of sales
max_idx = data["Sales"].idxmax()
highlight_month = data.loc[max_idx, "Month"]
highlight_sales = data.loc[max_idx, "Sales"]
plt.plot(data["Month"], data["Sales"], label="Sales")
plt.scatter([highlight_month], [highlight_sales], color="red", zorder=5, label="Highest")
plt.title("Highlighting Highest Sales Month")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Save your plot as an image file
plt.figure(figsize=(8,4))
plt.plot(data["Month"], data["Sales"], marker="o")
plt.title("Shampoo Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig("shampoo_sales_plot.png")
plt.close()
print("Plot saved as shampoo_sales_plot.png")
# Input: Let us ask the user for a line color
color = input("What color should the sales line be? For example, blue or orange: ")
plt.plot(data["Month"], data["Sales"], color=color, marker="o")
plt.title("Sales with Your Chosen Color")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Adding grid lines
plt.plot(data["Month"], data["Sales"], marker="o")
plt.title("Sales with Grid Lines")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Comparing two data series
import numpy as np
data["Random"] = np.random.randint(50, 200, size=len(data))
plt.plot(data["Month"], data["Sales"], marker="o", label="Sales")
plt.plot(data["Month"], data["Random"], marker="x", label="Random Numbers", linestyle=":")
plt.title("Comparing Two Series")
plt.xlabel("Month")
plt.ylabel("Value")
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Mini-project: Visualize Trends and Peaks#
Task: Draw a chart of shampoo sales that shows both monthly values and a dotted line for average sales.
This will help you spot above-average and below-average months.
# Mini-project Part 1: draw both sales and average sales
avg_sales = data["Sales"].mean()
plt.plot(data["Month"], data["Sales"], marker="o", label="Monthly Sales")
plt.hlines(avg_sales, xmin=0, xmax=len(data)-1, colors="red", linestyles="dotted", label="Average Sales")
plt.title("Monthly Sales vs Average")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Mini-project Part 2: highlight months above average
above_avg = data["Sales"] > avg_sales
plt.plot(data["Month"], data["Sales"], marker="o", label="Sales")
plt.scatter(data["Month"][above_avg], data["Sales"][above_avg], color="orange", label="Above Average")
plt.hlines(avg_sales, xmin=0, xmax=len(data)-1, colors="red", linestyles="dotted", label="Average")
plt.title("Highlighting Months Above Average")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Troubleshooting: if the plot does not show
print("Did you forget plt.show() or made a typo in the column name?")
# Recap: What did we learn?
print("You learned to make line and bar plots, customize them, and work with real data using Matplotlib!")
Challenge: Try It Yourself!#
Pick any dataset you care about.
- It could be sports scores, temperatures, or your favorite music trends.
Make a line plot, add custom colors, and label everything.
Share your results below or with a friend!
Thanks for watching!#
If you enjoyed this beginner lesson, subscribe for more Python and data science tips.
Let us keep exploring together!
See you in the next video.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



