study_notes.
md 2025-05-28
Matplotlib Tutorial Study Notes
Overview
This tutorial introduces Matplotlib, a powerful Python library for data visualization. It covers the basics of
creating various types of plots (line graphs, bar charts, histograms, pie charts, and box-and-whisker plots) and
demonstrates real-world applications using datasets like gas prices and FIFA player stats. The notes are
organized to help you understand Matplotlib's functionality, customize plots, and combine it with Pandas for
data analysis.
1. Getting Started with Matplotlib
Prerequisites
Libraries Required:
Matplotlib: For plotting.
NumPy: For numerical operations and arrays.
Pandas: For handling CSV data.
Installation:
Install via pip:
pip install matplotlib numpy pandas
Or use Anaconda, which includes these packages.
Importing Libraries:
import [Link] as plt
import numpy as np
import pandas as pd
Key Resource
Always refer to the Matplotlib Documentation (linked in the video description) for commands and
parameters. Use Ctrl+F to search for specific functions like plot, title, or legend.
2. Creating a Basic Line Graph
Steps to Create a Line Graph
1. Define Data:
1/9
study_notes.md 2025-05-28
Use 1D arrays for x and y values.
Example:
x = [0, 1, 2, 3, 4]
y = [0, 2, 4, 6, 8] # y = 2x
2. Plot the Graph:
[Link](x, y)
[Link]() # Displays the graph and removes extra output in Jupyter
Notebook
Customizing the Line Graph
Title:
[Link]("Our First Graph")
Axis Labels:
[Link]("X-Axis")
[Link]("Y-Axis")
Font Customization:
Use a font dictionary to change font properties (e.g., size, family, weight).
Example:
font_dict = {"family": "Comic Sans MS", "size": 20, "weight": "bold"}
[Link]("Our First Graph", fontdict=font_dict)
[Link]("X-Axis", fontdict={"family": "Arial", "size": 16})
Check Matplotlib documentation for available fonts.
Tick Marks:
Customize x and y ticks for clarity.
Example:
2/9
study_notes.md 2025-05-28
[Link]([0, 1, 2, 3, 4]) # Integer ticks
[Link]([0, 2, 4, 6, 8, 10]) # Ticks every 2 units
Legend:
Add a label to the plot for the legend.
Example:
[Link](x, y, label="2x")
[Link]() # Automatically places legend
Line Styling:
Customize color, linewidth, markers, and linestyle.
Example (longhand):
[Link](x, y, color="red", linewidth=2, marker="o", markersize=10,
markeredgecolor="black")
Shorthand Notation:
[Link](x, y, "ro--", label="2x") # Red, circle markers, dashed line
Refer to documentation for supported colors, markers, and linestyles.
Figure Size and DPI:
Set figure dimensions and resolution.
Example:
[Link](figsize=(5, 3), dpi=300) # 5x3 inches, 300 DPI
Saving the Graph:
Save as PNG with specified DPI.
Example:
[Link]("my_graph.png", dpi=300)
3/9
study_notes.md 2025-05-28
Adding Multiple Lines
Plot multiple lines on the same graph.
Example with a squared function using NumPy:
x2 = [Link](0, 4.5, 0.5)
[Link](x2, x2**2, "r", label="x^2") # Red line for x^2
[Link](x, y, "b", label="2x") # Blue line for 2x
[Link]()
[Link]()
Use NumPy's arange for smooth curves with decimal increments.
Plotting Projections
Show a dashed line for projected data.
Example:
[Link](x[:4], y[:4], "b", label="2x") # Solid line for first 4 points
[Link](x[3:], y[3:], "b--", label="2x Projection") # Dashed for rest
[Link]()
[Link]()
3. Creating Bar Charts
Basic Bar Chart
Plot categorical data with bars.
Example:
labels = ["A", "B", "C"]
values = [1, 4, 2]
[Link](labels, values)
[Link]()
Customizing Bar Charts
Figure Size:
[Link](figsize=(6, 4))
4/9
study_notes.md 2025-05-28
Hatch Patterns:
Add patterns to bars for visual distinction.
Example:
bars = [Link](labels, values)
bars[0].set_hatch("/") # Diagonal lines
bars[1].set_hatch("o") # Circles
bars[2].set_hatch("*") # Stars
[Link]()
Alternative (loop for multiple bars):
patterns = ["/", "o", "*"]
for bar, pattern in zip(bars, patterns):
bar.set_hatch(pattern)
Legend (optional, often unnecessary if labels are clear).
4. Real-World Examples with Pandas
Loading Data
Use Pandas to read CSV files.
Example:
gas = pd.read_csv("gas_prices.csv")
Save CSV files in the same directory as your script or specify the path.
Gas Prices Line Graph
Dataset: Gas prices over time for various countries (in USD per gallon).
Plotting:
[Link](figsize=(8, 5))
[Link](gas["Year"], gas["USA"], "b.-", label="United States")
[Link](gas["Year"], gas["Canada"], "r.-", label="Canada")
[Link](gas["Year"], gas["South Korea"], "g.-", label="South Korea")
[Link]("Gas Prices Over Time (USD)")
[Link]("Year")
[Link]("US Dollars")
5/9
study_notes.md 2025-05-28
[Link](gas["Year"][::3]) # Every 3rd year
[Link]()
[Link]("gas_price_figure.png", dpi=300)
[Link]()
Tips:
Use bracket notation (gas["South Korea"]) for column names with spaces.
Loop through countries for scalability:
for country in [Link][1:]: # Skip "Year" column
[Link](gas["Year"], gas[country], ".-", label=country)
FIFA Player Data Analysis
Histogram: Player Skill Levels
Dataset: FIFA player stats with columns like Overall, Preferred Foot, Weight, Club.
Plotting a Histogram:
fifa = pd.read_csv("fifa_data.csv")
bins = range(0, 101, 10) # Bins from 0 to 100, step 10
[Link](fifa["Overall"], bins=bins, color="#1f77b4")
[Link](bins)
[Link]("Distribution of Player Skills in FIFA")
[Link]("Skill Level")
[Link]("Number of Players")
[Link]()
Tips:
Adjust bins to focus on relevant ranges (e.g., 40–100 for FIFA ratings).
Use hexadecimal colors or color pickers for custom colors.
Pie Chart: Preferred Foot
Objective: Show percentage of players with left vs. right foot preference.
Processing Data:
left = [Link][fifa["Preferred Foot"] == "Left"].count()[0]
right = [Link][fifa["Preferred Foot"] == "Right"].count()[0]
Plotting:
6/9
study_notes.md 2025-05-28
[Link]([left, right], labels=["Left", "Right"], colors=["#ff9999",
"#66b3ff"], autopct="%.2f%%")
[Link]("Preferred Foot of FIFA Players")
[Link]()
Pie Chart: Weight Distribution
Objective: Show weight categories of FIFA players.
Processing Data:
Convert weight strings (e.g., "150lbs") to integers:
fifa["Weight"] = [int([Link]("lbs")) if isinstance(x, str) else x for
x in fifa["Weight"]]
light = [Link][fifa["Weight"] < 125].count()[0]
medium_light = [Link][(fifa["Weight"] >= 125) & (fifa["Weight"] <
150)].count()[0]
medium = [Link][(fifa["Weight"] >= 150) & (fifa["Weight"] <
175)].count()[0]
medium_heavy = [Link][(fifa["Weight"] >= 175) & (fifa["Weight"] <
200)].count()[0]
heavy = [Link][fifa["Weight"] >= 200].count()[0]
Plotting:
weights = [light, medium_light, medium, medium_heavy, heavy]
labels = ["Under 125", "125-150", "150-175", "175-200", "Over 200"]
explode = [0.4, 0, 0, 0, 0.4] # Explode small segments
[Link]("ggplot") # Apply ggplot style
[Link](weights, labels=labels, autopct="%1.2f%%", pctdistance=0.8,
explode=explode)
[Link]("Weight Distribution of FIFA Players (lbs)")
[Link]()
Tips:
Use explode to separate small pie slices.
Adjust pctdistance to position percentage labels.
Use styles like ggplot for better color schemes.
Box-and-Whisker Plot: Team Comparison
Objective: Compare overall ratings of players from different teams (e.g., FC Barcelona, Real Madrid,
New England Revolution).
7/9
study_notes.md 2025-05-28
Processing Data:
barcelona = [Link][fifa["Club"] == "FC Barcelona"]["Overall"]
madrid = [Link][fifa["Club"] == "Real Madrid"]["Overall"]
revs = [Link][fifa["Club"] == "New England Revolution"]["Overall"]
Plotting:
[Link](figsize=(5, 8))
boxes = [Link]([barcelona, madrid, revs], labels=["FC Barcelona", "Real
Madrid", "NE Revolution"], patch_artist=True)
for box in boxes["boxes"]:
[Link](facecolor="#e0e0e0", edgecolor="black", linewidth=2)
[Link]([barcelona, madrid, revs], labels=["FC Barcelona", "Real
Madrid", "NE Revolution"],
medianprops={"linewidth": 2})
[Link]("Professional Soccer Team Comparison")
[Link]("FIFA Overall Rating")
[Link]()
Tips:
Set patch_artist=True to enable facecolor customization.
Use medianprops to style the median line.
Box plots show the median, quartiles, and outliers for team comparisons.
5. Tips for Effective Plotting
Documentation: Always check the Matplotlib documentation for commands and parameters.
Google and Stack Overflow: Search for specific issues (e.g., "move legend outside Matplotlib graph").
Experiment with Styles: Use [Link]("ggplot") or other styles for better aesthetics.
High DPI for Saving: Use dpi=300 for high-resolution images.
Clean Code: Organize data and plotting steps logically to avoid errors.
Jupyter Notebook: Use [Link]() to suppress unwanted output.
6. Additional Resources
Matplotlib Documentation: Official guide for commands and examples.
GitHub Data: Download gas prices and FIFA datasets from the presenter's GitHub (linked in the video
description).
Pandas Tutorial: Review the presenter's Pandas video for data manipulation techniques.
Color Pickers: Use online tools to select hexadecimal colors for plots.
7. Practice Exercises
8/9
study_notes.md 2025-05-28
1. Create a line graph comparing gas prices for two additional countries from the dataset.
2. Build a histogram of FIFA player ages with custom bins and colors.
3. Design a pie chart for another FIFA attribute (e.g., nationality distribution).
4. Compare three additional soccer teams using a box-and-whisker plot.
8. Key Takeaways
1. Matplotlib is versatile for creating various plot types.
2. Combine with Pandas for real-world data analysis.
3. Customize plots extensively with titles, labels, colors, and styles.
Use documentation and online resources to troubleshoot and enhance visualizations.
9/9