sparc_spread sparc_spread - 17 days ago 11
Python Question

Matplotlib bar plot with pandas Timestamp

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

Answer

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

Comments