← Back to Chapters

Python Matplotlib

? Python Matplotlib

? Quick Overview

Matplotlib is a powerful Python library for data visualization. It lets you create high-quality 2D plots such as line graphs, bar charts, scatter plots, histograms, and pie charts. It is widely used in data analysis, scientific computing, and machine learning to understand and present data visually.

? Key Concepts

  • matplotlib.pyplot (imported as plt) is the main interface for plotting.
  • Plots are created using functions like plot(), bar(), scatter(), hist(), and pie().
  • Labels, titles, legends, and grid make plots easier to read and understand.
  • Subplots let you display multiple plots in a single figure window.
  • Matplotlib works very well with NumPy and Pandas for handling data.

? Syntax and Basics

The typical Matplotlib workflow looks like this:

  • Import the library: import matplotlib.pyplot as plt
  • Prepare your data (lists, NumPy arrays, or Pandas Series).
  • Create the plot using an appropriate function (line, bar, scatter, etc.).
  • Customize titles, axis labels, colors, and more.
  • Render the plot with plt.show().
? Basic Matplotlib Pattern
import matplotlib.pyplot as plt

# 1. Prepare data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

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

# 3. Customize plot
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# 4. Display plot
plt.show()

? Installing Matplotlib

Install Matplotlib using pip from your terminal or command prompt:

? Installation Command
# Install matplotlib using pip
pip install matplotlib

? Code Examples

? Basic Line Plot

The simplest visualization is a line plot using plt.plot() and plt.show().

? Simple Line Plot
import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Create a line plot
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

? Bar and Column Charts

Bar charts are used to compare values across categories.

? Bar Chart Example
import matplotlib.pyplot as plt

# Define categories and their values
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]

# Create and display bar chart
plt.bar(categories, values, color='skyblue')
plt.title("Bar Chart Example")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.show()

? Scatter Plots

Scatter plots show the relationship between two numeric variables.

? Scatter Plot Example
import matplotlib.pyplot as plt

# Sample x and y data points
x = [5, 7, 8, 7, 2, 17, 2, 9]
y = [99, 86, 87, 88, 100, 86, 103, 87]

# Create scatter plot and show it
plt.scatter(x, y, color='red', marker='o')
plt.title("Scatter Plot Example")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

⚙️ Customizing Plots

You can change colors, line styles, markers, grids, and add legends to make plots more informative.

? Customized Line Plot
import matplotlib.pyplot as plt

# Define x and y values
x = [1, 2, 3, 4, 5]
y = [10, 5, 8, 12, 7]

# Plot with custom style and labels
plt.plot(x, y, color='green', linestyle='--', marker='o', label='Line 1')
plt.title("Customized Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Add grid, legend, and show plot
plt.grid(True)
plt.legend()
plt.show()

? Subplots

Subplots let you show multiple related plots side by side in a single figure.

? Subplots Example
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [2, 3, 5, 7, 11]
y2 = [1, 4, 6, 8, 10]

plt.subplot(1, 2, 1)  # 1 row, 2 columns, 1st plot
plt.plot(x, y1, 'r-o')
plt.title("Plot 1")

plt.subplot(1, 2, 2)  # 2nd plot
plt.plot(x, y2, 'b-s')
plt.title("Plot 2")

plt.tight_layout()
plt.show()

? Histograms

Histograms display the frequency distribution of numerical data.

? Histogram Example
import matplotlib.pyplot as plt

# Sample data for the histogram
data = [1,2,2,3,3,3,4,4,4,4,5,5,5,6]

# Plot histogram and label axes
plt.hist(data, bins=6, color='purple', edgecolor='black')
plt.title("Histogram Example")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()

? Pie Charts

Pie charts represent parts of a whole as slices of a circle.

? Pie Chart Example
import matplotlib.pyplot as plt

# Define slice sizes and labels
sizes = [30, 25, 20, 25]
labels = ['A', 'B', 'C', 'D']

# Draw the pie chart and show percentages
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title("Pie Chart Example")
plt.show()

? Use Cases

  • Visualizing trends in time-series data (stock prices, sensor readings, etc.).
  • Comparing categories such as sales by region or product type.
  • Exploring relationships between variables using scatter plots.
  • Understanding data distribution with histograms.
  • Presenting percentage breakdowns using pie charts.

? Live Output / Explanation

? What the Plots Show

  • Simple Line Plot: A straight line showing how y increases as x increases.
  • Bar Chart: Vertical bars comparing categories A, B, C, and D and their values.
  • Scatter Plot: Dots scattered over the plane, showing how two variables relate to each other.
  • Customized Plot: A dashed green line with circle markers, grid lines, and a legend.
  • Subplots: Two different line charts displayed side by side in a single window.
  • Histogram: Bars showing how frequently each numeric value (or range) appears in the data.
  • Pie Chart: A circle divided into slices representing each category’s percentage share.

? Tips & Best Practices

  • Always label your axes and add a clear, descriptive title.
  • Use plt.tight_layout() when working with subplots to avoid overlapping elements.
  • Explore matplotlib.pyplot.style.use('ggplot') or other styles for a quick visual upgrade.
  • Combine Matplotlib with NumPy or Pandas for efficient data handling.
  • Choose appropriate plot types: line for trends, bar for categories, scatter for relationships, etc.

? Try It Yourself / Practice Tasks

  • Create a line plot comparing two sets of data with different colors and markers.
  • Make a bar chart showing sales for each month and customize the bar colors.
  • Plot a histogram of random numbers generated with numpy.random.randint().
  • Create a subplot with a scatter plot and a line plot side by side.
  • Draw a pie chart showing percentages of your favorite fruits.