Knio
Knio

Reputation: 7090

Pandas DataFrame.plot resets pyplot current figure

I'm trying to use pandas to plot to as specific figure, but it seems to want to make it's own figures and not use / resets pyplot's current figure.

How can I make pandas plot to the current (or better yet, and explicitly given) figure?

from matplotlib import pyplot
import pandas

df = pandas.DataFrame({'a': list(range(1000))})
fig1 = pyplot.figure(figsize=(5, 10))
assert pyplot.gcf() is fig1 # succeeds
df.plot() # does not draw to fig1
assert pyplot.gcf() is fig1 # fails

Upvotes: 1

Views: 2419

Answers (2)

Uvar
Uvar

Reputation: 3462

The solution is quite easy. You can specify to which axes object the plot needs to refer. This can be done by getting the current handle from ax = pyplot.gca(), subsequently plotting to this handle. Of course, you can always plot to another handle as well using similar syntax.

from matplotlib import pyplot
import pandas

df = pandas.DataFrame({'a':list(range(1000))})
fig1 = pyplot.figure(figsize=(5, 10))
ax = pyplot.gca()
assert pyplot.gcf() is fig1 # succeeds
df.plot(ax=ax) # draws to fig1 now
assert pyplot.gcf() is fig1 # Succeeds now, too

Upvotes: 6

Jonathan Eunice
Jonathan Eunice

Reputation: 22443

Not exactly your question, but may address your need via different mechanism:

If you just want to set the figure size, you can pass pyplot kwargs to df.plot:

df.plot(figsize=(5, 10))
pyplot.show()

Upvotes: 0

Related Questions