Pandas: Plot multiple timer columns with labels (example from pandas documentation)

I am trying to recreate an example of plotting multiple timer columns 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 looks 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 only plot one column:

ts['A'].plot()

      

I am getting the result.

Is there a way to debug this to see what's going on here?

+3


source to share


1 answer


The reason you are not getting the result is because you are not storing the "correct" digit: you make a figure with plt.figure()

, but pandas does not display the current digit and creates a new one.
If you do:

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

      

I am getting correct output. When building the series, it uses the current axis if no axis is passed.
But it seems that the pandas docs are not quite correct on this account (as they are using plt.figure()

), I reported an issue for this: https://github.com/pydata/pandas/issues/8776

Another option is to provide an axes object with an argument ax

:



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

      

+3


source







All Articles