16.5. Data visualization with matplotlib
Table of Contents
Why visualization matters in data science
Visualization turns raw numbers into pictures you can understand at a glance. With graphs, you can:
- See trends over time
- Compare groups
- Spot outliers (unusual values)
- Explain results to others quickly
In Python, one of the most common libraries for plotting is matplotlib, usually used through its pyplot module.
Getting started with matplotlib
To follow along, you should already know how to:
- Install and import Python libraries
- Work with basic data (lists, numbers)
- Use simple NumPy/pandas examples (from this chapter’s earlier sections)
Most examples will use this import style:
import matplotlib.pyplot as plt
This gives you access to plotting functions through plt.
A basic pattern you’ll see a lot:
import matplotlib.pyplot as plt
# 1. Prepare your data
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
# 2. Create a plot
plt.plot(x, y)
# 3. Show the plot window
plt.show()
plt.show() opens a window (or displays the figure in a notebook) with your chart.
Basic plot types
Line plots
Line plots are useful for showing how something changes, often over time.
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5, 6, 7]
temperatures = [21, 23, 20, 22, 24, 25, 23]
plt.plot(days, temperatures) # x, y
plt.xlabel("Day")
plt.ylabel("Temperature (°C)")
plt.title("Temperature Over One Week")
plt.show()You can customize the line style and color:
plt.plot(days, temperatures, color="red", linestyle="--", marker="o")Common options:
- Colors:
"red","blue","green"or shorthand like"r","b","g" - Line styles:
"-"(solid),"--"(dashed),"-.",":" - Markers:
"o"(circle),"s"(square),"x","^"(triangle), etc.
Scatter plots
Scatter plots show individual points. They’re useful for exploring relationships between two variables.
import matplotlib.pyplot as plt
hours_studied = [1, 2, 3, 4, 5, 6]
exam_score = [50, 55, 65, 70, 75, 85]
plt.scatter(hours_studied, exam_score)
plt.xlabel("Hours Studied")
plt.ylabel("Exam Score")
plt.title("Study Time vs Exam Score")
plt.show()You can change marker style and color:
plt.scatter(hours_studied, exam_score, color="purple", marker="x")Bar charts
Bar charts compare values across categories (like labels instead of numbers on the x-axis).
import matplotlib.pyplot as plt
languages = ["Python", "JavaScript", "C++", "Java"]
popularity = [85, 75, 60, 70] # Made-up scores
plt.bar(languages, popularity)
plt.xlabel("Programming Language")
plt.ylabel("Popularity Score")
plt.title("Programming Language Popularity (Example Data)")
plt.show()You can change color, width, and orientation:
plt.bar(languages, popularity, color="orange")Horizontal bar chart:
plt.barh(languages, popularity) # Note: barh = horizontal bar chartHistograms
Histograms show the distribution of a numeric variable—how often values fall into ranges (bins).
import matplotlib.pyplot as plt
ages = [18, 19, 21, 22, 23, 19, 34, 45, 29, 31, 22, 25, 26, 27, 30, 32, 40]
plt.hist(ages, bins=5) # Try changing number of bins
plt.xlabel("Age")
plt.ylabel("Frequency")
plt.title("Age Distribution")
plt.show()
The bins parameter controls how many bars (ranges) the histogram will have.
Customizing plots
Good plots are not just correct—they’re readable and clear. Here are some simple customizations.
Titles and axis labels
Use:
plt.title("Your Title")plt.xlabel("X-axis label")plt.ylabel("Y-axis label")
Example:
plt.plot([1, 2, 3], [3, 5, 7])
plt.title("Simple Line")
plt.xlabel("X value")
plt.ylabel("Y value")
plt.show()Legends
Legends explain different lines or markers in one figure.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y1 = [2, 4, 6, 8]
y2 = [1, 3, 5, 7]
plt.plot(x, y1, label="Group A")
plt.plot(x, y2, label="Group B")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Two Lines on One Plot")
plt.legend() # Show legend
plt.show()You can position the legend:
plt.legend(loc="upper left") # or "upper right", "lower right", "lower left", etc.Colors and styles
To keep multiple lines distinct:
plt.plot(x, y1, color="blue", linestyle="-", marker="o", label="Blue line")
plt.plot(x, y2, color="red", linestyle="--", marker="s", label="Red dashed line")You can also use short format strings:
plt.plot(x, y1, "bo-") # blue, circle markers, solid line
plt.plot(x, y2, "r--") # red, dashed lineFigure size
Change the size of the whole figure:
plt.figure(figsize=(8, 4)) # width, height in inches
plt.plot(x, y1)
plt.title("Custom Size")
plt.show()
You typically call plt.figure() before plotting.
Using matplotlib with NumPy and pandas
In data science, you often load and manipulate data with NumPy and pandas, then plot it with matplotlib.
Plotting a NumPy array
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100) # 100 points from 0 to 10
y = np.sin(x)
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.title("Sine Wave")
plt.show()Plotting a pandas DataFrame
pandas integrates nicely with matplotlib. A simple example:
import pandas as pd
import matplotlib.pyplot as plt
data = {
"day": [1, 2, 3, 4, 5],
"steps": [3000, 5000, 7000, 6500, 8000]
}
df = pd.DataFrame(data)
plt.plot(df["day"], df["steps"])
plt.xlabel("Day")
plt.ylabel("Steps")
plt.title("Daily Step Count")
plt.show()
pandas also has its own plotting methods (which use matplotlib under the hood), but here we focus on using plt directly.
Subplots: multiple charts in one figure
Subplots let you show several related charts side by side in a single figure.
Use plt.subplot(rows, columns, index) where:
rows= number of rows of plotscolumns= number of columnsindex= which plot (starting at 1)
Example with 2 subplots (1 row, 2 columns):
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125]
plt.figure(figsize=(10, 4))
# Left plot
plt.subplot(1, 2, 1)
plt.plot(x, y1)
plt.title("Squares")
# Right plot
plt.subplot(1, 2, 2)
plt.plot(x, y2)
plt.title("Cubes")
plt.tight_layout() # Adjust layout to avoid overlap
plt.show()
tight_layout() helps prevent titles and labels from overlapping.
Saving plots to files
Instead of (or in addition to) showing a figure on screen, you can save it to a file with plt.savefig().
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 3, 5, 7]
plt.plot(x, y)
plt.title("Example Plot")
plt.savefig("example_plot.png") # Save as PNG
plt.show()
Supported formats include .png, .jpg, .pdf, .svg, etc. The format is chosen from the file extension.
You can control the resolution with dpi:
plt.savefig("example_plot_highres.png", dpi=300)Common beginner pitfalls with matplotlib
- Forgetting
plt.show()
In many environments, you must callplt.show()to actually display the figure. - Plotting before creating a figure (in more complex scripts)
While not always required, explicitplt.figure()can help keep complex scripts organized. - Overlapping labels or text
If labels overlap, try:
plt.tight_layout()or rotate labels:
plt.xticks(rotation=45)- Data lengths don’t match
xandyinplt.plot(x, y)(orplt.scatter) must have the same length. - Too many colors and styles
Simpler is often better. Use a small, consistent set of colors and line styles.
Small practice ideas
Here are a few mini tasks to practice:
- Line chart of monthly expenses
- Create a list of 12 numbers (one for each month).
- Plot them as a line chart with appropriate labels and title.
- Histogram of random data
- Use NumPy or Python’s
randommodule to generate 100 random integers. - Plot a histogram of the values.
- Comparing two categories
- Create two lists of numbers (e.g., scores of Class A and Class B).
- Plot them as side-by-side bar charts or as two lines on the same plot with a legend.
- Multiple subplots
- In one figure, create:
- A line plot in the first subplot
- A histogram in the second
- Use
plt.subplot()andplt.tight_layout().
These exercises will help you get comfortable turning data into clear visual stories using matplotlib.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!