Module 15 of 25 · Mastering Numpy and Pandas for Data Analysis · Beginner

Introduction to Matplotlib

Duration: 5 min

This module provides an introduction to Matplotlib, a powerful plotting library in Python. You will learn how to create various types of plots, customize their appearance, and understand the basic structure of Matplotlib. This skill is crucial for data visualization, a key component in data science for exploring and presenting data insights.

Basic Plotting with Matplotlib

Matplotlib allows you to create a wide variety of plots. The most basic plot is a line plot, which can be created using the plot function. You need to import Matplotlib and use its pyplot module to access plotting functions. The plot function takes two arrays of equal length representing the x and y coordinates of the points to be plotted.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# Create a line plot
plt.plot(x, y)

# Add title and labels
plt.title('Simple Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Display the plot
plt.show()

Try it in Google Colab: Open in Colab

A line plot with points at (1,2), (2,3), (3,5), (4,7), and (5,11) is displayed. The plot has a title 'Simple Line Plot' and labeled axes.

Customizing Plots

Matplotlib provides extensive customization options for plots. You can change the line style, color, add markers, and more. Additionally, you can create subplots to display multiple plots in a single figure.

import matplotlib.pyplot as plt

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

# Create subplots
fig, axs = plt.subplots(2)

# First subplot
axs[0].plot(x, y1, 'g--')  # Green dashed line
axs[0].set_title('First Subplot')

# Second subplot
axs[1].plot(x, y2, 'r^')  # Red triangles
axs[1].set_title('Second Subplot')

# Display the plots
plt.tight_layout()
plt.show()

💡 Tip: When creating subplots, use plt.tight_layout() to automatically adjust subplot parameters to give specified padding.

❓ What function is used to create a line plot in Matplotlib?

❓ Which method is used to add a title to a plot in Matplotlib?

Key Concepts

Concept Description
Figures Core principle in this module
Axes Core principle in this module
Styling Core principle in this module
Customization Core principle in this module

Check Your Understanding

❓ What is the main purpose of Introduction?

❓ Which of these is a key characteristic of Introduction?

← Previous Continue interactively → Next →

Related Courses