Lesson 9 · Data visualisation in python
How to Create and Customize Scatter Plots and Histograms in Matplotlib
We will explore two of the most useful plots for understanding data: scatter plots and histograms. This lesson is for absolute beginners. We will go step by…
- CourseData visualisation in python
- Lesson9 of 34
- Video15 min
- FormatJupyter notebook · 17 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbWelcome to Scatter Plots and Histograms in Python!#
We will explore two of the most useful plots for understanding data: scatter plots and histograms.
This lesson is for absolute beginners. We will go step by step, learning how to load data, plot it, and read what the plots mean.
You will also try some practical exercises and see a mini-project example using real-world sales data.
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import matplotlib.pyplot as plt
Data setup#
We will use a real retail sales dataset called Shampoo Sales. This data shows monthly shampoo sales over three years.
We will load the data from a CSV file straight from the internet.
# Download and load shampoo sales data
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/shampoo.csv"
shampoo = pd.read_csv(url)
print("Shape:", shampoo.shape)
print(shampoo.head())
# Check column names and types
print(shampoo.dtypes)
shampoo['Month'] = pd.date_range(start='1901-01', periods=shampoo.shape[0], freq='M')
shampoo['Month'] = pd.to_datetime(shampoo['Month'])
# Line plot to visualize sales over time
plt.figure(figsize=(8,4))
plt.plot(shampoo['Month'], shampoo['Sales'])
plt.title("Monthly Shampoo Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
What is a scatter plot?#
A scatter plot is a type of graph that uses dots to show the relationship between two numeric variables. Each dot shows a pair of values.
Scatter plots can show patterns, clusters, and if two things are related.
# Simple scatter plot: Month vs. Sales
plt.figure(figsize=(8,4))
plt.scatter(shampoo['Month'], shampoo['Sales'], color='teal')
plt.title("Scatter Plot: Shampoo Sales Over Time")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
# Creating a synthetic example: Advertising vs. Sales
import numpy as np
np.random.seed(0)
shampoo['Advertising'] = np.random.randint(200, 400, size=shampoo.shape[0])
# Scatter plot of Advertising vs Sales
plt.figure(figsize=(8,4))
plt.scatter(shampoo['Advertising'], shampoo['Sales'], c='green')
plt.title("Sales vs. Advertising")
plt.xlabel("Advertising Spend")
plt.ylabel("Sales")
plt.show()
What is a histogram?#
A histogram helps show how often values appear in a dataset. It groups values into 'bins' and shows how many fall into each bin with bars.
Histograms are great to see where most values lielike seeing which sales are common or rare.
# Show Histogram of Sales data
plt.figure(figsize=(8,4))
plt.hist(shampoo['Sales'], bins=8, color='skyblue', edgecolor='black')
plt.title("Distribution of Monthly Sales")
plt.xlabel("Sales")
plt.ylabel("Number of Months")
plt.show()
# Try with fewer or more bins
plt.figure(figsize=(8,4))
plt.hist(shampoo['Sales'], bins=3, color='salmon', edgecolor='white', alpha=0.8)
plt.title("Histogram with 3 Bins")
plt.xlabel("Sales")
plt.ylabel("Count")
plt.show()
# Compare two different columns in one histogram
plt.figure(figsize=(8,4))
plt.hist([shampoo['Sales'], shampoo['Advertising']], bins=8, alpha=0.7, label=['Sales','Advertising'])
plt.title("Sales vs. Advertising Distributions")
plt.xlabel("Value")
plt.ylabel("Number of Months")
plt.legend()
plt.show()
Handling missing or bad data in plots#
Real datasets sometimes have missing or unusual values. These can confuse plots.
It is a good habit to check for missing numbers before plotting and to decide how to handle them.
# Check for missing values
print(shampoo.isnull().sum())
# Drop missing values just in case
shampoo_clean = shampoo.dropna()
How histograms and scatter plots help in real life#
Businesses use scatter plots to find trends and patterns. Histograms show what is normal or rare. Both help make better decisions, faster.
Let us try a mini-project to explore this more.
# Mini-project: Find months with top 5 highest sales
top_months = shampoo_clean.sort_values(by='Sales', ascending=False).head(5)
print(top_months[['Month', 'Sales']])
# Visualize top 5 sales months on a scatter plot
plt.figure(figsize=(8,4))
plt.scatter(shampoo_clean['Month'], shampoo_clean['Sales'], label='All Months', alpha=0.5)
plt.scatter(top_months['Month'], top_months['Sales'], color='red', label='Top 5 Months', s=80)
plt.title("Sales: Top 5 Months Highlighted")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.show()
# Practice: Try your own histogram with user input
import builtins
column = input("Type 'Sales' or 'Advertising': ")
if column in shampoo_clean.columns:
plt.figure(figsize=(8,4))
plt.hist(shampoo_clean[column], bins=6, color='gold', edgecolor='black')
plt.title(f"Histogram of {column}")
plt.xlabel(column)
plt.ylabel("Count")
plt.show()
else:
print("Column not found.")
Tips for clearer plots#
- Always label your axes and add titles.
- Use colors to highlight differences.
- Adjust bin sizes or dot sizes to avoid clutter.
- Try different plot types with the same data to get new insights.
# Challenge: Make a scatter plot with different dot sizes
sizes = (shampoo_clean['Advertising'] - shampoo_clean['Advertising'].min()) * 0.8
plt.figure(figsize=(8,4))
plt.scatter(shampoo_clean['Month'], shampoo_clean['Sales'], s=sizes, alpha=0.6, color='purple')
plt.title("Sales with Dot Sizes by Advertising")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
Recap: What did we learn?#
- How to use pandas and matplotlib for plots.
- What scatter plots and histograms show, and their best uses.
- How to load, check, and clean real data before plotting.
- Ways to highlight data for business insight.
With these skills, you can start exploring any new dataset!
Thanks for learning with us!#
If this lesson helped you, please like and subscribe to our channel.
Try your own scatter plots and histograms on a dataset you are curious about.
Happy coding!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



