bjelli
bjelli

Reputation: 10090

pandas: plot multiple columns of a timeseries with labels (example from pandas documentation)

I'm trying to recreate the example of plot multiple columns of a timeseries with labels as shown in the pandas documentation here: http://pandas.pydata.org/pandas-docs/dev/visualization.html#visualization-basic (second graph)

multiple columns of a timeseries with labels

Here's my code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

ts = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=1000), columns=list('ABCD'))
ts = ts.cumsum()
fig = plt.figure()

print ts.head()
ts.plot()
fig.savefig("x.png")

the text output seems ok:

                   A         B         C         D
2000-01-01  1.547838 -0.571000 -1.780852  0.559283
2000-01-02  1.165659 -1.859979 -0.490980  0.796502
2000-01-03  0.786416 -2.543543 -0.903669  1.117328
2000-01-04  1.640174 -3.756809 -1.862188  0.466236
2000-01-05  2.119575 -4.590741 -1.055563  1.004607

but x.png is always empty.

If I plot just one column:

ts['A'].plot()

I do get a result.

Is there a way to debug this, to find out what's going wrong here?

Upvotes: 4

Views: 12851

Answers (1)

joris
joris

Reputation: 139162

The reason you don't get a result is because you are not saving the 'correct' figure: you are making a figure with plt.figure(), but pandas does not plot on the current figure, and will create a new one.
If you do:

ts.plot()
fig = plt.gcf()  # get current figure
fig.savefig("x.png")

I get the correct output. When plotting a Series, it does use the current axis if no axis is passed.
But it seems that the pandas docs are not fully correct on that account (as they use the plt.figure()), I reported an issue for that: https://github.com/pydata/pandas/issues/8776

Another option is to provide an axes object using the ax argument:

fig = plt.figure()
ts.plot(ax=plt.gca())  # 'get current axis'
fig.savefig("x.png")

or slightly cleaner (IMO):

fig, ax = plt.subplots()
ts.plot(ax=ax)
fig.savefig("x.png")

Upvotes: 4

Related Questions