Martin B.
Martin B.

Reputation: 1928

Running fig = plt.figure() in pandas opens two figures

Pretty much what it says in the title.. most pandas examples suggest doing fig = plt.figure() before df.plot(..). But if I do that, two figures pop up after plt.show() - the first completely empty and the second with the actual pandas figure.. Any ideas why?

Upvotes: 1

Views: 810

Answers (1)

joris
joris

Reputation: 139172

On a DataFrame, df.plot(..) will create a new figure, unless you provide an Axes object to the ax keyword argument.
So you are correct that the plt.figure() is not needed in this case. The plt.figure() calls in the pandas documentation should be removed, as they indeed are not needed. There is an issue about this: https://github.com/pydata/pandas/issues/8776

What you can do with the ax keyword is eg:

fig, ax = plt.subplots()
df.plot(..., ax=ax)

Note that when plotting a series, this will by default plot on the 'current' axis (plt.gca()) if you don't provide ax.

Upvotes: 2

Related Questions