4

I am having trouble making this very simple example work:

from numpy import datetime64
from pandas import Series
import matplotlib.pyplot as plt
import datetime

x = Series ([datetime64("2016-01-01"),datetime64("2016-02-01")]).astype(datetime)
y = Series ([0.1 , 0.2])

ax = plt.subplot(111)
ax.bar(x, y, width=10)
ax.xaxis_date()

plt.show()

The error I get is:

TypeError: float() argument must be a string or a number, not 'Timestamp'

Note the astype(datetime) piece - that is something I tried after reading this other SO post. Without that piece, I get the same error.

On the other hand, the example works well enough with plain datetime64 types - that is, changing these two lines:

x = [datetime64("2016-01-01"),datetime64("2016-02-01")]
y = [0.1 , 0.2]

So the issue must be the Timestamp type that pandas converts the datetime64 objects into. Is there a way to make this work with Timestamp directly, and not revert to datetime64? I'm using Series/Timestamp here because my real objective is plotting series from a DataFrame. (Note: I cannot use the DataFrame plotting methods because my real example is inside a seaborn FacetGrid and I have to use matplotlib directly.)

Community
  • 1
  • 1
sparc_spread
  • 10,643
  • 11
  • 45
  • 59

2 Answers2

5

Use:

ax.bar(x.values, y, width=10)

when using the Series objects. The issue is that you are not sending an object that is similar to an array, it is an indexed array that matplotlib does not know how to handle. values returns only the array

elelias
  • 4,552
  • 5
  • 30
  • 45
1

As your objective is plotting series from a DataFrame, maybe you can just use pd.DataFrame.plot?

from numpy import datetime64
from pandas import Series
import matplotlib.pyplot as plt
import datetime
%matplotlib inline

x = Series ([datetime64("2016-01-01"),datetime64("2016-02-01")])
y = Series ([0.1 , 0.2])

df = pd.DataFrame({'x': x, 'y': y})
df.plot.bar(x='x', y='y')

image produced

Ilya V. Schurov
  • 7,687
  • 2
  • 40
  • 78
  • I wish! Unfortunately in my real problem I am working inside a seaborn `FacetGrid` and need to use `matplotlib` directly. – sparc_spread Nov 17 '16 at 17:08