Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Pandas Plotting Backend

In this lesson, you will learn how to create data visualizations directly from Pandas Series and DataFrame objects using Matplotlib. You will explore different plotting methods, chart types, customization options, and the Pandas plotting backend.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Understand Pandas plotting and its relationship with Matplotlib.
  • Understand the Pandas plotting backend.
  • Create charts directly from Pandas DataFrames.
  • Create charts using Pandas Series.
  • Generate line plots, bar charts, and scatter plots.
  • Create histograms and pie charts using Pandas.
  • Customize charts using plotting parameters.
  • Use Matplotlib Axes methods with Pandas plots.
  • Understand how to configure the Pandas plotting backend.

2. Introduction to Pandas Plotting

Pandas is a popular Python library used for data manipulation and analysis. It provides built-in plotting functionality that allows developers to create charts directly from Series and DataFrame objects.

Pandas uses Matplotlib as its default plotting backend. This means that when we create a chart using Pandas, Matplotlib is generally responsible for rendering the visualization.

Instead of manually passing every data column to Matplotlib, we can use the plot() method provided by Pandas.

Example: Student Performance Report

Suppose a teacher wants to display student marks for different subjects. The marks are already stored in a Pandas DataFrame.

Using Pandas plotting, the teacher can directly create a line chart or bar chart from the DataFrame without manually extracting each value.

3. Understanding Pandas Plotting Backend

A plotting backend is the library responsible for creating and rendering visualizations when Pandas plotting methods are used.

By default, Pandas uses the Matplotlib plotting backend. Pandas provides the plotting interface, while Matplotlib handles the actual chart rendering.

Pandas DataFrame / Series Plot Method DataFrame.plot() Matplotlib Chart Rendering Pandas provides plotting methods and Matplotlib renders the chart.
Figure 1: Basic workflow of Pandas plotting with Matplotlib.

4. Installing Required Libraries

Before using Pandas plotting, install Pandas and Matplotlib in your Python environment.

Installing Pandas and Matplotlib

pip install pandas matplotlib

Importing Required Libraries

import pandas as pd
import matplotlib.pyplot as plt

The alias pd is commonly used for Pandas, while plt is commonly used for Matplotlib Pyplot.

Checking Installed Versions

import pandas as pd
import matplotlib

print("Pandas Version:", pd.__version__)
print("Matplotlib Version:", matplotlib.__version__)

Output

Pandas Version: Installed Pandas version
Matplotlib Version: Installed Matplotlib version
Tip: If both libraries are already installed in your Python environment, you do not need to install them again.

5. Creating a Pandas DataFrame

A DataFrame is a two-dimensional data structure containing rows and columns. We can use its numerical columns to create different charts.

Example: Employee Sales Data

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Sales": [20000, 25000, 30000, 28000, 40000],
    "Profit": [4000, 5000, 6500, 6000, 9000]
}

df = pd.DataFrame(data)

print(df)

Output

  Month  Sales  Profit
0   Jan  20000    4000
1   Feb  25000    5000
2   Mar  30000    6500
3   Apr  28000    6000
4   May  40000    9000

The DataFrame contains three columns: Month, Sales, and Profit. We can use these columns directly for plotting.

6. Using the DataFrame.plot() Method

The DataFrame.plot() method is used to create charts directly from DataFrame data.

Syntax

DataFrame.plot(
    x=None,
    y=None,
    kind="line"
)

The x parameter selects the X-axis column, while y selects the Y-axis column or columns. The kind parameter specifies the chart type.

Basic Example

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr"],
    "Sales": [20000, 25000, 30000, 40000]
}

df = pd.DataFrame(data)

df.plot(x="Month", y="Sales")

plt.show()

Output

Chart Type: Line Plot

X-axis: Month
Y-axis: Sales

Jan - 20000
Feb - 25000
Mar - 30000
Apr - 40000

A line chart displays the monthly sales values.
Remember: Line plot is the default chart type when using the Pandas plot method.

7. Creating Line Plots Using Pandas

A line plot is useful for displaying changes in data over time or across ordered categories. Pandas supports line plots using kind="line".

Example

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Sales": [20000, 25000, 30000, 28000, 40000]
}

df = pd.DataFrame(data)

df.plot(
    x="Month",
    y="Sales",
    kind="line",
    marker="o",
    color="blue"
)

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales (₹)")
plt.grid(True, alpha=0.3)

plt.show()

Output

Chart Title: Monthly Sales

X-axis: Month
Y-axis: Sales (₹)

Jan - 20000
Feb - 25000
Mar - 30000
Apr - 28000
May - 40000

A blue line connects the monthly sales values.
Circular markers identify individual data points.

8. Creating Bar Charts Using Pandas

A bar chart is useful for comparing values across different categories. Pandas provides kind="bar" to create vertical bar charts.

Vertical Bar Chart

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Sales": [20000, 25000, 30000, 28000, 40000]
}

df = pd.DataFrame(data)

df.plot(
    x="Month",
    y="Sales",
    kind="bar",
    color="skyblue",
    legend=False
)

plt.title("Monthly Sales Comparison")
plt.xlabel("Month")
plt.ylabel("Sales (₹)")
plt.xticks(rotation=0)

plt.show()

Output

Chart Type: Vertical Bar Chart

Jan - 20000
Feb - 25000
Mar - 30000
Apr - 28000
May - 40000

Each month is represented by a separate vertical bar.
The height of each bar represents its sales value.

Horizontal Bar Chart

Use kind="barh" to create a horizontal bar chart.

df.plot(
    x="Month",
    y="Sales",
    kind="barh",
    color="orange",
    legend=False
)

plt.title("Monthly Sales - Horizontal Bar Chart")
plt.xlabel("Sales (₹)")
plt.ylabel("Month")

plt.show()

Output

Chart Type: Horizontal Bar Chart

Month names appear on the vertical axis.
Sales values appear on the horizontal axis.
Each month is represented by a horizontal bar.

9. Creating Scatter Plots Using Pandas

A scatter plot displays the relationship between two numerical variables. Each row in the DataFrame is represented by a point.

Example: Study Hours and Marks

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "StudyHours": [1, 2, 3, 4, 5, 6],
    "Marks": [35, 42, 50, 60, 75, 85]
}

df = pd.DataFrame(data)

df.plot(
    x="StudyHours",
    y="Marks",
    kind="scatter",
    color="green",
    s=80
)

plt.title("Study Hours vs Marks")
plt.xlabel("Study Hours")
plt.ylabel("Marks")
plt.grid(True, alpha=0.3)

plt.show()

Output

Chart Type: Scatter Plot

X-axis: Study Hours
Y-axis: Marks

Study Hours    Marks
1              35
2              42
3              50
4              60
5              75
6              85

Each row is represented by a green point.
The sample data shows an increasing relationship
between study hours and marks.

10. Creating Histograms Using Pandas

A histogram displays the distribution of numerical data by grouping values into intervals called bins.

Example: Student Marks Distribution

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Marks": [
        35, 40, 45, 50, 55,
        60, 65, 70, 75, 80,
        85, 90, 95
    ]
}

df = pd.DataFrame(data)

df["Marks"].plot(
    kind="hist",
    bins=5,
    color="purple",
    edgecolor="black"
)

plt.title("Marks Distribution")
plt.xlabel("Marks")
plt.ylabel("Frequency")

plt.show()

Output

Chart Type: Histogram

Data Column: Marks
Number of Bins: 5

The histogram groups marks into intervals.
The height of each bar represents the
number of observations in that interval.
Tip: Change the bins parameter to control the number of intervals used to group numerical data.

11. Creating Pie Charts Using Pandas

A pie chart displays the contribution of each category to a total. Pandas supports pie charts using kind="pie".

Example: Department-wise Employees

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Department": [
        "Development",
        "Testing",
        "Support",
        "HR"
    ],
    "Employees": [40, 25, 20, 15]
}

df = pd.DataFrame(data)

df.set_index("Department")["Employees"].plot(
    kind="pie",
    autopct="%1.1f%%",
    startangle=90
)

plt.title("Department-wise Employees")
plt.ylabel("")

plt.show()

Output

Chart Type: Pie Chart

Development: 40 employees (40%)
Testing:     25 employees (25%)
Support:     20 employees (20%)
HR:          15 employees (15%)

Each slice represents the percentage
of employees in a department.

12. Plotting a Pandas Series

A Pandas Series is a one-dimensional labelled data structure. We can create charts directly from a Series using its plot() method.

Example

import pandas as pd
import matplotlib.pyplot as plt

sales = pd.Series(
    [15000, 20000, 25000, 30000, 35000],
    index=["Jan", "Feb", "Mar", "Apr", "May"],
    name="Sales"
)

sales.plot(
    kind="line",
    marker="o",
    color="green"
)

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales (₹)")
plt.grid(True, alpha=0.3)

plt.show()

Output

Series Name: Sales

Jan    15000
Feb    20000
Mar    25000
Apr    30000
May    35000

A green line chart displays the Series values.
The Series index is used for X-axis labels.

13. Plotting Multiple DataFrame Columns

We can plot multiple numerical columns from a DataFrame in one chart. Each selected column is displayed as a separate data series.

Example: Business Performance

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Sales": [20000, 25000, 30000, 35000, 40000],
    "Profit": [4000, 5000, 6000, 7000, 9000],
    "Expenses": [10000, 12000, 15000, 17000, 18000]
}

df = pd.DataFrame(data)

df.plot(
    x="Month",
    y=["Sales", "Profit", "Expenses"],
    kind="line",
    marker="o",
    figsize=(9, 5)
)

plt.title("Monthly Business Report")
plt.xlabel("Month")
plt.ylabel("Amount (₹)")
plt.grid(True, alpha=0.3)

plt.show()

Output

Chart Title: Monthly Business Report

X-axis: Month
Y-axis: Amount (₹)

Three data series are displayed:
1. Sales
2. Profit
3. Expenses

Each series has a separate line and legend entry.
Important: When plotting columns with very different value ranges, smaller values may be difficult to see. Consider using separate charts when the comparison is not clear.

14. Important Parameters of DataFrame.plot()

Pandas provides several parameters to control the appearance and behaviour of charts.

Parameter Purpose Example
x Selects the X-axis column. x="Month"
y Selects the Y-axis column or columns. y="Sales"
kind Specifies the chart type. kind="bar"
title Sets the chart title. title="Sales"
color Sets the chart colour. color="blue"
figsize Sets the figure dimensions. figsize=(8, 5)
grid Enables or disables grid lines. grid=True
legend Controls legend visibility. legend=True
alpha Controls transparency. alpha=0.7
rot Controls axis label rotation. rot=45

Example Using Multiple Parameters

df.plot(
    x="Month",
    y="Sales",
    kind="line",
    title="Monthly Sales",
    color="blue",
    figsize=(9, 5),
    grid=True,
    legend=True,
    rot=45
)

plt.show()

Output

A line chart is created with:

Title: Monthly Sales
Line colour: Blue
Figure size: 9 x 5 inches
Grid: Enabled
Legend: Enabled
X-axis labels: Rotated by 45 degrees

15. Customizing Pandas Plots Using Matplotlib Axes

The Pandas plotting method returns a Matplotlib Axes object. We can store this object in a variable and use Matplotlib methods to customize the chart.

Example

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr"],
    "Sales": [20000, 30000, 25000, 40000]
}

df = pd.DataFrame(data)

# Create Pandas plot
ax = df.plot(
    x="Month",
    y="Sales",
    kind="line",
    marker="o",
    color="blue"
)

# Customize using Matplotlib Axes methods
ax.set_title("Monthly Sales Report")
ax.set_xlabel("Month")
ax.set_ylabel("Sales (₹)")

ax.grid(True, linestyle="--", alpha=0.5)

plt.tight_layout()
plt.show()

Output

Chart Title: Monthly Sales Report

X-axis Label: Month
Y-axis Label: Sales (₹)

The chart is created using Pandas.
Its returned Axes object is customized
using Matplotlib methods.
Tip: This is an important feature of Pandas plotting. You can use simple Pandas plotting syntax and still access Matplotlib's detailed customization options.

16. Configuring the Pandas Plotting Backend

Pandas supports a plotting backend configuration. The default backend is Matplotlib, but the plotting backend can be changed to another compatible plotting library.

Checking the Current Backend

import pandas as pd

print(pd.options.plotting.backend)

Output

matplotlib

Setting the Matplotlib Backend

import pandas as pd

pd.options.plotting.backend = "matplotlib"

print(pd.options.plotting.backend)

Output

matplotlib

Using set_option()

import pandas as pd

pd.set_option(
    "plotting.backend",
    "matplotlib"
)

print(pd.get_option("plotting.backend"))

Output

matplotlib
Note: A different plotting backend may require an additional library to be installed. The available chart types and supported parameters can vary between backends.

17. Handling Missing Values Before Plotting

Real-world datasets may contain missing values. Before creating visualizations, it is important to check and handle missing data.

Example Using dropna()

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr"],
    "Sales": [20000, None, 30000, 40000]
}

df = pd.DataFrame(data)

# Remove rows containing missing values
clean_df = df.dropna()

clean_df.plot(
    x="Month",
    y="Sales",
    kind="line",
    marker="o"
)

plt.title("Sales After Removing Missing Values")
plt.show()

Output

Original Data:
Jan    20000
Feb    NaN
Mar    30000
Apr    40000

After dropna():

Jan    20000
Mar    30000
Apr    40000

A line chart is created using the remaining records.

18. Best Practices for Pandas Plotting

Recommended Practices

  • Select only the columns required for the chart.
  • Use meaningful chart titles and axis labels.
  • Choose the correct chart type for your data.
  • Use legends when displaying multiple data series.
  • Adjust figure size for better readability.
  • Use Matplotlib Axes methods for additional customization.
  • Check missing values before plotting.
  • Use separate charts when data ranges are very different.
Important: Always choose a chart type according to the data you are analysing. A chart should make the information easier to understand, not more confusing.

19. Classroom Practical Activity

Activity: Student Performance Analysis

Create a Pandas DataFrame using the following student performance data.

Student Maths Science English
Rahul 85 80 75
Priya 90 88 92
Amit 70 75 80
Sneha 95 90 94

Complete the following activities:

  1. Create a line chart for all three subjects.
  2. Create a bar chart to compare student marks.
  3. Create a scatter plot using Maths and Science marks.
  4. Add a chart title and axis labels.
  5. Display a legend for all subjects.

20. Practice Questions

Beginner Level

  1. What is Pandas plotting?
  2. Which plotting library is used by Pandas by default?
  3. What is the purpose of the DataFrame.plot() method?
  4. How do you create a bar chart using Pandas?
  5. What is the difference between a Series and a DataFrame?

Intermediate Level

  1. Create a line chart using monthly sales data.
  2. Create a horizontal bar chart using department data.
  3. Display multiple DataFrame columns in one line chart.
  4. Customize a Pandas plot using a Matplotlib Axes object.
  5. Change the Pandas plotting backend configuration.

Summary

In this lesson, you learned how Pandas provides built-in plotting methods for creating charts directly from Series and DataFrame objects. Matplotlib is the default plotting backend used by Pandas to render visualizations.

You explored different chart types such as line plots, bar charts, horizontal bar charts, scatter plots, histograms, and pie charts using the Pandas plot method.

You also learned how to customize charts using plotting parameters and Matplotlib Axes methods. The plotting backend configuration allows Pandas to work with compatible plotting libraries.

Understanding Pandas plotting helps developers create visualizations quickly while working with structured datasets and performing data analysis.