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.
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
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.
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.
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.
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.
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
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.
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:
- Create a line chart for all three subjects.
- Create a bar chart to compare student marks.
- Create a scatter plot using Maths and Science marks.
- Add a chart title and axis labels.
- Display a legend for all subjects.
20. Practice Questions
Beginner Level
- What is Pandas plotting?
- Which plotting library is used by Pandas by default?
- What is the purpose of the
DataFrame.plot()method? - How do you create a bar chart using Pandas?
- What is the difference between a Series and a DataFrame?
Intermediate Level
- Create a line chart using monthly sales data.
- Create a horizontal bar chart using department data.
- Display multiple DataFrame columns in one line chart.
- Customize a Pandas plot using a Matplotlib Axes object.
- 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.