How to return a matplotlib.figure.Figure object from Pandas plot function?

MatplotlibPythonData Visualization

To return a matplotlib.figure.Figure object from Pandas function, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Create a Pandas dataframe, df.
  • Make a horizontal bar plot using barh() method.
  • Get the current figure instance.
  • Place a legend on the axes at the lower-right location.
  • To display the figure, use show() method.


from matplotlib import pyplot as plt
import pandas as pd

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame({'a': range(10)})
ax = df.plot.barh(color=(1, 0, 0, 0.25))
fig = ax.get_figure()
ax.legend(loc='lower right')


Updated on 16-Jun-2021 12:19:21