Matplotlib条形图与熊猫时间戳

时间:2016-11-17 16:44:08

标签: python pandas numpy matplotlib

我在制作这个非常简单的示例时遇到了麻烦:

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

我得到的错误是:

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

请注意astype(datetime)件 - 这是我在reading this other SO post之后尝试过的。没有那件,我得到同样的错误。

另一方面,该示例适用于普通datetime64类型 - 也就是说,更改这两行:

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

因此问题必须是pandas将Timestamp对象转换为的datetime64类型。有没有办法直接使用Timestamp,而不是恢复为datetime64?我在这里使用Series / Timestamp因为我的真正目标是从DataFrame绘制系列。 (注意:我不能使用DataFrame绘图方法,因为我的真实例子是在seaborn FacetGrid内,我必须直接使用matplotlib。)

2 个答案:

答案 0 :(得分:3)

使用:

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

使用Series对象时。问题是你没有发送一个类似于数组的对象,它是matplotlib不知道如何处理的索引数组。 values仅返回数组

答案 1 :(得分:1)

由于您的目标是从DataFrame绘制系列,也许您可​​以使用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

相关问题