Python 带时间戳的Matplotlib条形图
我很难让这个非常简单的例子起作用:Python 带时间戳的Matplotlib条形图,python,pandas,numpy,matplotlib,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
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)
piece-这是我尝试过的。没有那一块,我也会犯同样的错误
另一方面,该示例在使用普通的datetime64
类型时效果很好,即更改这两行:
x = [datetime64("2016-01-01"),datetime64("2016-02-01")]
y = [0.1 , 0.2]
因此,问题必须是pandas将datetime64
对象转换为的Timestamp
类型。是否有一种方法可以直接使用时间戳
,而不恢复到日期时间64
?我在这里使用系列
/时间戳
,因为我的真正目标是从数据帧
绘制系列。(注意:我不能使用DataFrame
绘图方法,因为我的真实示例位于seabornFaceGrid
中,我必须直接使用matplotlib。)使用:
ax.bar(x.values, y, width=10)
使用系列对象时。问题在于,您发送的对象不是类似于数组的对象,而是matplotlib不知道如何处理的索引数组<代码>值仅返回数组因为您的目标是从数据帧绘制序列,也许您可以使用
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')
我希望如此!不幸的是,在我真正的问题中,我在seaborn
FaceGrid
中工作,需要直接使用matplotlib
。