1

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

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

5 Comments

df = pandas.DataFrame(range(1000)) results in: Traceback (most recent call last): ... .... ... ValueError: DataFrame constructor not properly called!
the DataFrame constructor works fine on my Pandas (0.19.2)
I'm using pandas 0.20.3 ... so I think it will be the usual case in the future. But if it is a biggie, I'll remove it from the answer, as it has nothing to do with the solution indeed
Yeah, not related to the question, I just needed some sample data. I updated the question to use your constructor to avoid any confusion
A final note on supplying range to DataFrame. This is more an issue of using python 3 versus python 2. In python 3 you'd need to convert to list first, pd.DataFrame(list(range(1000))).
0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.