Matplotlib Introduction

Matplotlib Introduction in Python: A picture is worth a thousand numbers. If you have a spreadsheet with 10,000 rows of sales data, it's hard to see a trend.

Concept Explanation

A picture is worth a thousand numbers. If you have a spreadsheet with 10,000 rows of sales data, it's hard to see a trend. But if you turn that data into a simple line chart, the trend becomes obvious instantly.

Matplotlib is the most popular data visualization library in Python. It is older than most modern libraries, meaning it is incredibly stable, works everywhere, and can create almost any type of chart you can imagine—from simple bar graphs to complex 3D surface maps. It is the "grandfather" of Python plotting.


Syntax or Core Structure

The pyplot module

Almost all interaction with Matplotlib happens through matplotlib.pyplot. The community standard is to import it as plt.

import matplotlib.pyplot as plt

# 1. Prepare data
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

# 2. Create the plot
plt.plot(x, y)

# 3. Add labels
plt.title("Growth Chart")
plt.xlabel("Days")
plt.ylabel("Value")

# 4. Show the result
plt.show()

Code Example #1 (Basic)

Creating a simple Bar Chart to compare categories.

import matplotlib.pyplot as plt

fruits = ["Apples", "Bananas", "Cherries"]
popularity = [10, 25, 15]

plt.bar(fruits, popularity, color="skyblue")
plt.title("Fruit Popularity")
plt.show()

Code Example #2 (Intermediate)

Customizing styles and adding multiple lines.

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]
temp_london = [20, 22, 21, 19, 23]
temp_paris = [25, 27, 24, 26, 28]

plt.plot(days, temp_london, label="London", marker="o", linestyle="--")
plt.plot(days, temp_paris, label="Paris", marker="s")

plt.legend() # Shows the labels
plt.grid(True) # Adds a background grid
plt.show()

Real World Example

Stock Trend Analysis: Visualizing the fluctuate of a stock over a week.

import matplotlib.pyplot as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
prices = [150.2, 148.5, 152.0, 155.8, 154.1]

plt.figure(figsize=(10, 5)) # Set the size of the image
plt.plot(days, prices, color="green", linewidth=2)

# Highlighting the highest point
plt.annotate("Weekly High", xy=("Thu", 155.8), xytext=("Wed", 156),
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.title("TechCorp Stock Price")
plt.ylabel("Price (USD)")
plt.show()

Common Mistakes

  1. Forgetting plt.show(): If you write all the plotting code but forget plt.show(), nothing will happen! The window won't open.
  2. Shape Mismatch: Trying to plot x with 5 items and y with 4 items. Matplotlib will throw a ValueError. Both must have the same length.
  3. Messy Charts: Overloading a single chart with too much data. If you have 50 lines on one chart, nobody can read it. Use plt.subplot() to create separate small charts instead.

Best Practices

  • Label Everything: Never share a chart without a Title, X-axis label, and Y-axis label.
  • Use Styles: Matplotlib has built-in themes! Try plt.style.use('ggplot') or plt.style.use('seaborn') for professional-looking charts instantly.
  • Save to File: Instead of just showing the plot, use plt.savefig("chart.png") to save your work for presentations or websites.

Practice Exercises

  1. The Pie Chart: Use plt.pie() to create a chart showing how you spent your time yesterday (e.g., Sleep: 8h, Work: 8h, Fun: 8h).
  2. Scatter Plot: Create an array of 50 random x and y coordinates and plot them using plt.scatter().
  3. Sin Wave: Challenge! Use NumPy to generate a range of numbers from 0 to 10, calculate the sine of those numbers, and plot the wave.