Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to return a matplotlib.figure.Figure object from Pandas plot function?
To return a matplotlib.figure.Figure object from a Pandas plot function, you need to access the underlying matplotlib axes object and then retrieve its figure. This is useful when you want to manipulate the figure properties or save it programmatically.
Basic Approach
The key is to use the get_figure() method on the axes object returned by any Pandas plotting method ?
import pandas as pd
import matplotlib.pyplot as plt
# Create sample data
df = pd.DataFrame({'values': [10, 25, 30, 45, 20]})
# Create plot and get axes object
ax = df.plot.bar()
# Get the figure object from axes
fig = ax.get_figure()
# Verify the type
print(f"Figure type: {type(fig)}")
print(f"Figure size: {fig.get_size_inches()}")
plt.show()
Figure type: <class 'matplotlib.figure.Figure'> Figure size: [6.4 4.8]
Complete Example with Figure Manipulation
Here's a comprehensive example showing how to retrieve and manipulate the figure object ?
import pandas as pd
import matplotlib.pyplot as plt
# Set figure parameters
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create DataFrame
df = pd.DataFrame({
'Category A': [10, 15, 20, 25, 30],
'Category B': [5, 12, 18, 22, 28]
})
# Create horizontal bar plot
ax = df.plot.barh(color=['red', 'blue'], alpha=0.7)
# Get the figure object
fig = ax.get_figure()
# Manipulate the figure
fig.suptitle('Sales Data Comparison')
ax.legend(loc='lower right')
ax.set_xlabel('Values')
# You can now work with the figure object
print(f"Figure object: {fig}")
print(f"Number of axes: {len(fig.axes)}")
plt.show()
Figure object: <matplotlib.figure.Figure object at 0x...> Number of axes: 1
Alternative Methods
You can also access the figure using plt.gcf() (get current figure) ?
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'data': [1, 2, 3, 4, 5]})
# Create plot
df.plot()
# Get current figure
fig = plt.gcf()
print(f"Figure retrieved: {type(fig)}")
print(f"Figure has {len(fig.axes)} axes")
plt.show()
Figure retrieved: <class 'matplotlib.figure.Figure'> Figure has 1 axes
Common Use Cases
| Method | Use Case | When to Use |
|---|---|---|
ax.get_figure() |
Direct figure access | When you have the axes object |
plt.gcf() |
Current figure access | When working with current plot |
fig, ax = plt.subplots() |
Create figure first | When you need figure control upfront |
Conclusion
Use ax.get_figure() to retrieve the matplotlib Figure object from any Pandas plot. This gives you full control over figure properties, saving options, and advanced customization beyond what Pandas plotting provides.
