2016-11-17 59 views
2

我无法使这个非常简单的例子的工作: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] 

所以这个问题必须Timestamp型,大熊猫的datetime64对象转换成。有没有办法使这个工作直接与Timestamp,而不是恢复到datetime64?我在这里使用Series/Timestamp,因为我的真正目标是绘制DataFrame系列。 (注:因为我真实的例子是seaborn FacetGrid内,我必须直接使用matplotlib我不能使用DataFrame绘制方法。)

回答

3

用途:

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

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

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

+0

我的心愿!不幸的是,在我真正的问题中,我正在使用一个“FacetGrid”,需要直接使用'matplotlib'。 –